Leetcode 1971: Find if Path Exists in Graph

grid47
grid47
Exploring patterns and algorithms
Apr 23, 2024 7 min read

You are given a graph with n vertices labeled from 0 to n-1 (inclusive) and edges connecting pairs of vertices. Your task is to determine if there exists a valid path from a given source vertex to a destination vertex. The graph is undirected, and each pair of vertices is connected by at most one edge. The vertices are connected by edges as given in the input.
Problem
Approach
Steps
Complexity
Input: The input consists of the following components: an integer `n`, representing the number of vertices, a 2D array `edges` representing the edges between vertices, and two integers `source` and `destination` which are the starting and ending vertices respectively.
Example: n = 4, edges = [[0,1],[1,2],[2,3]], source = 0, destination = 3
Constraints:
• 1 <= n <= 2 * 10^5
• 0 <= edges.length <= 2 * 10^5
• edges[i].length == 2
• 0 <= ui, vi <= n - 1
• ui != vi
• 0 <= source, destination <= n - 1
• There are no duplicate edges.
• There are no self edges.
Output: The output should be a boolean value, `true` if there is a valid path from the source to the destination vertex, and `false` otherwise.
Example: Output: true
Constraints:
• The solution must be able to handle large graphs efficiently.
Goal: To determine if a valid path exists from the source to the destination vertex by performing a breadth-first search (BFS) or depth-first search (DFS) in the graph.
Steps:
• Step 1: Represent the graph using an adjacency list where each vertex points to a list of connected vertices.
• Step 2: Use BFS (or DFS) starting from the source vertex to explore all reachable vertices.
• Step 3: If the destination vertex is found during the traversal, return `true`.
• Step 4: If the traversal completes without visiting the destination vertex, return `false`.
Goal: The input graph must meet the given constraints for `n`, edges, and vertex values.
Steps:
• The graph is undirected and has no self edges.
• The graph can have up to 200,000 vertices and edges, so an efficient solution is required.
Assumptions:
• The graph is connected and there may be multiple paths from source to destination.
Input: Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2
Explanation: In this case, there is a direct path from vertex 0 to vertex 2, or a path through vertex 1 (0 -> 1 -> 2), so the output is `true`.

Input: Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
Explanation: In this case, there is no path from vertex 0 to vertex 5, so the output is `false`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus