Find a Path in a Graph
Medium graphs · bfs
Description
Constraints
1 <= n <= 100000
Examples
Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], src = 0, dst = 5
Output: false
Hints (1)
- Flood fill from the source and check whether the destination is reached.
Solutions
DFS from source. · Time O(V+E) · Space O(V+E)
func hasPath(n int, edges [][]int, src, dst int) bool {
adj := make([][]int, n)
for _, e := range edges {
adj[e[0]] = append(adj[e[0]], e[1])
adj[e[1]] = append(adj[e[1]], e[0])
}
seen := make([]bool, n)
stack := []int{src}
for len(stack) > 0 {
u := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if u == dst {
return true
}
if seen[u] {
continue
}
seen[u] = true
for _, v := range adj[u] {
if !seen[v] {
stack = append(stack, v)
}
}
}
return false
}
DFS from source. · Time O(V+E) · Space O(V+E)
function hasPath(n, edges, src, dst) {
const adj = Array.from({ length: n }, () => []);
for (const [u, v] of edges) { adj[u].push(v); adj[v].push(u); }
const seen = new Array(n).fill(false);
const stack = [src];
while (stack.length) {
const u = stack.pop();
if (u === dst) return true;
if (seen[u]) continue;
seen[u] = true;
for (const v of adj[u]) if (!seen[v]) stack.push(v);
}
return false;
}
DFS from source. · Time O(V+E) · Space O(V+E)
function hasPath($n, $edges, $src, $dst) {
$adj = array_fill(0, $n, []);
foreach ($edges as $e) { $adj[$e[0]][] = $e[1]; $adj[$e[1]][] = $e[0]; }
$seen = array_fill(0, $n, false); $stack = [$src];
while ($stack) {
$u = array_pop($stack);
if ($u === $dst) return true;
if ($seen[$u]) continue;
$seen[$u] = true;
foreach ($adj[$u] as $v) { if (!$seen[$v]) $stack[] = $v; }
}
return false;
}
DFS from source. · Time O(V+E) · Space O(V+E)
def hasPath(n, edges, src, dst):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
seen = [False] * n
stack = [src]
while stack:
u = stack.pop()
if u == dst:
return True
if seen[u]:
continue
seen[u] = True
for v in adj[u]:
if not seen[v]:
stack.append(v)
return False
DFS from source. · Time O(V+E) · Space O(V+E)
function hasPath(n: number, edges: number[][], src: number, dst: number): boolean {
const adj: number[][] = Array.from({ length: n }, () => []);
for (const [u, v] of edges) { adj[u].push(v); adj[v].push(u); }
const seen = new Array(n).fill(false);
const stack = [src];
while (stack.length) {
const u = stack.pop()!;
if (u === dst) return true;
if (seen[u]) continue;
seen[u] = true;
for (const v of adj[u]) if (!seen[v]) stack.push(v);
}
return false;
}
Create a free account to submit solutions, track progress and save problems.
Create account