Skip to content

Commit 9e742d9

Browse files
committed
solve graph valid tree
1 parent e294a1d commit 9e742d9

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

graph-valid-tree/sora0319.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
public class Solution {
2+
public boolean validTree(int n, int[][] edges) {
3+
Map<Integer, List<Integer>> graph = new HashMap<>();
4+
for (int i = 0; i < n; i++) {
5+
graph.put(i, new ArrayList<>());
6+
}
7+
8+
for (int[] edge : edges) {
9+
int node = edge[0];
10+
int adj = edge[1];
11+
graph.get(node).add(adj);
12+
graph.get(adj).add(node);
13+
}
14+
15+
Set<Integer> visited = new HashSet<>();
16+
if (inCycle(0, -1, graph, visited)) {
17+
return false;
18+
}
19+
20+
return visited.size() == n;
21+
}
22+
23+
private boolean inCycle(int node, int prev, Map<Integer, List<Integer>> graph, Set<Integer> visited) {
24+
if (visited.contains(node)) {
25+
return true;
26+
}
27+
28+
visited.add(node);
29+
30+
for (int neighbor : graph.get(node)) {
31+
if (neighbor == prev) continue;
32+
if (inCycle(neighbor, node, graph, visited)) {
33+
return true;
34+
}
35+
}
36+
37+
return false;
38+
}
39+
}
40+

0 commit comments

Comments
 (0)