-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1971. Find if Path Exists in Graph
More file actions
37 lines (31 loc) · 1.03 KB
/
1971. Find if Path Exists in Graph
File metadata and controls
37 lines (31 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
https://leetcode.com/problems/find-if-path-exists-in-graph/description/
Time: O(V+E)
Space: O(V+E)
class Solution {
public boolean validPath(int n, int[][] edges, int source, int destination) {
Map<Integer, List<Integer>> graph = new HashMap<>();
Stack<Integer> stack = new Stack<>();
for (int[] edge : edges) {
int a = edge[0];
int b = edge[1];
graph.computeIfAbsent(a, val -> new ArrayList<>()).add(b);
graph.computeIfAbsent(b, val -> new ArrayList<>()).add(a);
}
boolean[] seen = new boolean[n];
seen[source] = true;
stack.push(source);
while(!stack.isEmpty()) {
int curr = stack.pop();
if (curr == destination) {
return true;
}
for (int next : graph.get(curr)) {
if (!seen[next]) {
seen[next] = true;
stack.push(next);
}
}
}
return false;
}
}