-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path261_Graph Valid Tree.java
More file actions
43 lines (41 loc) · 1.12 KB
/
261_Graph Valid Tree.java
File metadata and controls
43 lines (41 loc) · 1.12 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
class Solution {
public boolean validTree(int n, int[][] edges) {
Map<Integer, List<Integer>> map = new HashMap<>();
int[] status = new int[n];
for (int i = 0; i < n; ++i) {
map.put(i, new ArrayList<>());
}
for (int[]edge: edges) {
map.get(edge[0]).add(edge[1]);
map.get(edge[1]).add(edge[0]);
}
if (!dfs(0, -1, map, status)) {
return false;
}
for (int i = 0; i < n; ++i) {
if(status[i] != 2) {
return false;
}
}
return true;
}
private boolean dfs(int cur, int prev, Map<Integer, List<Integer>> map, int[] status) {
if (status[cur] == 2) {
return true;
}
if (status[cur] == 1) {
return false;
}
status[cur] = 1;
for (int next: map.get(cur)) {
if (next == prev) {
continue;
}
if (!dfs(next, cur, map, status)) {
return false;
}
}
status[cur] = 2;
return true;
}
}