Skip to content

Commit f2315d0

Browse files
authored
Update Find if Path Exists in Graph - Leetcode 1971.java
1 parent 105ecb7 commit f2315d0

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.java

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,68 @@ private boolean dfs(int node, int destination, Map<Integer, List<Integer>> graph
3030
return false;
3131
}
3232
}
33+
34+
35+
// Iterative DFS With Stack
36+
import java.util.*;
37+
38+
public class Solution {
39+
public boolean validPath(int n, int[][] edges, int source, int destination) {
40+
if (source == destination) return true;
41+
42+
Map<Integer, List<Integer>> graph = new HashMap<>();
43+
for (int[] edge : edges) {
44+
graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]);
45+
graph.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]);
46+
}
47+
48+
Set<Integer> seen = new HashSet<>();
49+
Stack<Integer> stack = new Stack<>();
50+
stack.push(source);
51+
seen.add(source);
52+
53+
while (!stack.isEmpty()) {
54+
int node = stack.pop();
55+
if (node == destination) return true;
56+
for (int neighbor : graph.getOrDefault(node, Collections.emptyList())) {
57+
if (!seen.contains(neighbor)) {
58+
seen.add(neighbor);
59+
stack.push(neighbor);
60+
}
61+
}
62+
}
63+
return false;
64+
}
65+
}
66+
67+
// BFS With Queue
68+
import java.util.*;
69+
70+
public class Solution {
71+
public boolean validPath(int n, int[][] edges, int source, int destination) {
72+
if (source == destination) return true;
73+
74+
Map<Integer, List<Integer>> graph = new HashMap<>();
75+
for (int[] edge : edges) {
76+
graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]);
77+
graph.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]);
78+
}
79+
80+
Set<Integer> seen = new HashSet<>();
81+
Queue<Integer> queue = new LinkedList<>();
82+
queue.offer(source);
83+
seen.add(source);
84+
85+
while (!queue.isEmpty()) {
86+
int node = queue.poll();
87+
if (node == destination) return true;
88+
for (int neighbor : graph.getOrDefault(node, Collections.emptyList())) {
89+
if (!seen.contains(neighbor)) {
90+
seen.add(neighbor);
91+
queue.offer(neighbor);
92+
}
93+
}
94+
}
95+
return false;
96+
}
97+
}

0 commit comments

Comments
 (0)