forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsora0319.java
More file actions
40 lines (32 loc) · 1.01 KB
/
sora0319.java
File metadata and controls
40 lines (32 loc) · 1.01 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
public class Solution {
public boolean validTree(int n, int[][] edges) {
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int i = 0; i < n; i++) {
graph.put(i, new ArrayList<>());
}
for (int[] edge : edges) {
int node = edge[0];
int adj = edge[1];
graph.get(node).add(adj);
graph.get(adj).add(node);
}
Set<Integer> visited = new HashSet<>();
if (inCycle(0, -1, graph, visited)) {
return false;
}
return visited.size() == n;
}
private boolean inCycle(int node, int prev, Map<Integer, List<Integer>> graph, Set<Integer> visited) {
if (visited.contains(node)) {
return true;
}
visited.add(node);
for (int neighbor : graph.get(node)) {
if (neighbor == prev) continue;
if (inCycle(neighbor, node, graph, visited)) {
return true;
}
}
return false;
}
}