-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_1971_FindIfPathExistsInGraph_BFS.java
More file actions
80 lines (55 loc) · 2.23 KB
/
_1971_FindIfPathExistsInGraph_BFS.java
File metadata and controls
80 lines (55 loc) · 2.23 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package src._3_bfs_dfs;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* <a href="https://leetcode.com/problems/find-if-path-exists-in-graph/">Find if Path Exists in Graph</a>
* <a href="https://www.youtube.com/watch?v=ZwGC60Ao6bQ&t=638s&ab_channel=AdityaVerma">8 Find if path exists | Graph</a>
*/
public class _1971_FindIfPathExistsInGraph_BFS {
public static void main(String[] args) {
_1971_FindIfPathExistsInGraph_BFS obj = new _1971_FindIfPathExistsInGraph_BFS();
int[][] edges = {{4, 3}, {1, 4}, {4, 8}, {1, 7}, {6, 4}, {4, 2}, {7, 4}, {4, 0}, {0, 9}, {5, 4}};
boolean isPathExists = obj.validPath(10, edges, 5, 9);
System.out.println(isPathExists);
}
public boolean validPath(int n, int[][] edges, int source, int destination) {
if (n == 1 || (source == destination)) return true;
List<List<Integer>> adjList = getAdjList(n, edges);
return doBFS(source, destination, n, adjList);
}
private boolean doBFS(int source, int destination, int n, List<List<Integer>> adjList) {
Queue<Integer> queue = new LinkedList<>();
boolean[] isVisited = new boolean[n];
queue.offer(source);
isVisited[source] = true;
while (!queue.isEmpty()) {
int currNode = queue.poll();
isVisited[currNode] = true;
for (int adjNode : adjList.get(currNode)) {
if (adjNode == destination) {
return true; // we've found a path between source to destination
}
if (!isVisited[adjNode]) {
isVisited[adjNode] = true;
queue.offer(adjNode);
}
}
}
return false;
}
private List<List<Integer>> getAdjList(int n, int[][] edges) {
List<List<Integer>> adjList = new ArrayList<>();
for (int i = 0; i < n; i++) {
adjList.add(new ArrayList<>());
}
for (int i = 0; i < edges.length; i++) {
int src = edges[i][0];
int dst = edges[i][1];
adjList.get(src).add(dst);
adjList.get(dst).add(src);
}
return adjList;
}
}