-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindIfPathExistsInGraph.java
More file actions
83 lines (76 loc) · 2.89 KB
/
FindIfPathExistsInGraph.java
File metadata and controls
83 lines (76 loc) · 2.89 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
81
82
83
package solutions;
import java.util.*;
// [Problem] https://leetcode.com/problems/find-if-path-exists-in-graph
class FindIfPathExistsInGraph {
// BFS
// O(v + e) time, O(v + e) space
public boolean validPathBfs(int n, int[][] edges, int source, int destination) {
HashSet<Integer>[] graph = new HashSet[n];
for (int i = 0; i < n; i++) {
graph[i] = new HashSet<>();
}
for (int[] edge : edges) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
boolean[] visited = new boolean[n];
Queue<Integer> nodesToVisit = new ArrayDeque<>();
nodesToVisit.add(source);
visited[source] = true;
while (!nodesToVisit.isEmpty()) {
int nextNodes = nodesToVisit.size();
for (int i = 0; i < nextNodes; i++) {
int node = nodesToVisit.poll();
if (node == destination) {
return true;
}
Set<Integer> connectedNodes = graph[node];
for (int connectedNode : connectedNodes) {
if (!visited[connectedNode]) {
nodesToVisit.add(connectedNode);
visited[node] = true;
}
}
}
}
return false;
}
// DFS
// O(v + e) time, O(v + e) space
public boolean validPath(int n, int[][] edges, int source, int destination) {
HashSet<Integer>[] graph = new HashSet[n];
for (int i = 0; i < n; i++) {
graph[i] = new HashSet<>();
}
for (int[] edge : edges) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
return dfs(graph, new boolean[n], source, destination);
}
private boolean dfs(HashSet<Integer>[] graph, boolean[] visited, int source, int destination) {
if (source == destination) {
return true;
}
visited[source] = true;
Set<Integer> connectedNodes = graph[source];
for (int connectedNode : connectedNodes) {
if (!visited[connectedNode] && dfs(graph, visited, connectedNode, destination)) {
return true;
}
}
return false;
}
// Test
public static void main(String[] args) {
FindIfPathExistsInGraph solution = new FindIfPathExistsInGraph();
int[][] edges1 = {{0, 1}, {1, 2}, {2, 0}};
boolean expectedOutput1 = true;
boolean actualOutput1 = solution.validPath(3, edges1, 0, 2);
System.out.println("Test 1 passed? " + (expectedOutput1 == actualOutput1));
int[][] edges2 = {{0, 1}, {0, 2}, {3, 5}, {5, 4}, {4, 3}};
boolean expectedOutput2 = false;
boolean actualOutput2 = solution.validPath(6, edges2, 0, 5);
System.out.println("Test 2 passed? " + (expectedOutput2 == actualOutput2));
}
}