-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1971FindIfPathExistsInGraph.java
More file actions
58 lines (51 loc) · 1.83 KB
/
1971FindIfPathExistsInGraph.java
File metadata and controls
58 lines (51 loc) · 1.83 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//https://leetcode.com/problems/find-if-path-exists-in-graph/
class Solution {
Map<Integer, List<Integer>> buildGraph(int[][] edges, int n) {
Map<Integer, List<Integer>> graph = new HashMap();
for(int i = 0; i < n; i++) {
graph.put(i, new ArrayList());
}
for(int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
}
return graph;
}
public boolean validPath(int n, int[][] edges, int source, int destination) {
Map<Integer, List<Integer>> graph = buildGraph(edges, n);
boolean[] visited = new boolean[n];
//return dfs(source, graph, visited, destination);
return bfs(source, graph, visited, destination);
}
boolean bfs(int source, Map<Integer, List<Integer>> graph, boolean[] visited, int destination) {
Queue<Integer> queue = new LinkedList();
queue.add(source);
while(!queue.isEmpty()) {
Integer top = queue.remove();
visited[top] = true;
if(top == destination) {
return true;
}
for(Integer neighbour : graph.get(top)) {
if(!visited[neighbour]) {
queue.add(neighbour);
}
}
}
return false;
}
boolean dfs(Integer currentNode, Map<Integer, List<Integer>> graph, boolean[] visited, int destination) {
if(currentNode == destination) {
return true;
}
visited[currentNode] = true;
for(Integer neighbour: graph.get(currentNode)) {
if(!visited[neighbour]) {
if(dfs(neighbour, graph, visited, destination)) {
return true;
}
}
}
return false;
}
}