-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC_1971
More file actions
41 lines (28 loc) · 946 Bytes
/
Copy pathLC_1971
File metadata and controls
41 lines (28 loc) · 946 Bytes
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
38
39
40
41
class Solution {
public boolean validPath(int n, int[][] edges, int source, int destination) {
List<Integer>[] graph = new ArrayList[n];
for(int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
for(int[] edge : edges) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
boolean[] visited = new boolean[n];
return dfs(source, destination, graph, visited);
}
private boolean dfs(int node, int destination,
List<Integer>[] graph,
boolean[] visited) {
if(node == destination)
return true;
visited[node] = true;
for(int neighbour : graph[node]) {
if(!visited[neighbour]) {
if(dfs(neighbour, destination, graph, visited))
return true;
}
}
return false;
}
}