Skip to content

Commit 236f699

Browse files
committed
#262 Graph Valid Tree
1 parent 63805ba commit 236f699

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

graph-valid-tree/forest000014.java

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
# Time Complexity: O(n)
3+
# Space Complexity: O(n + m)
4+
- m은 edges.length
5+
6+
# Solution
7+
edges[0][0]에서 출발하여 인접한 모든 edge를 DFS로 순회한다.
8+
- cycle이 있는 경우 (이미 방문한 적이 있는 node를 재방문)
9+
- 순회를 마쳤는데 방문하지 않은 node가 있는 경우
10+
위 2경우는 invalid tree이고, 그렇지 않으면 valid tree이다.
11+
*/
12+
class Solution {
13+
public ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
14+
public boolean[] visited;
15+
public boolean validTree(int n, int[][] edges) {
16+
if (edges.length == 0) {
17+
return n == 1;
18+
}
19+
20+
visited = new boolean[n];
21+
22+
for (int i = 0; i < n; i++) {
23+
adj.add(new ArrayList<Integer>());
24+
}
25+
26+
for (int i = 0; i < edges.length; i++) {
27+
int a = edges[i][0];
28+
int b = edges[i][1];
29+
adj.get(a).add(b);
30+
adj.get(b).add(a);
31+
}
32+
33+
if (!dfs(-1, edges[0][0])) {
34+
return false;
35+
}
36+
37+
for (int i = 0; i < n; i++) {
38+
if (!visited[i]) {
39+
return false;
40+
}
41+
}
42+
43+
return true;
44+
}
45+
46+
public boolean dfs(int prev, int curr) {
47+
visited[curr] = true;
48+
49+
for (Integer next : adj.get(curr)) {
50+
if (next == prev) {
51+
continue;
52+
}
53+
54+
if (visited[next]) {
55+
return false;
56+
}
57+
58+
if (!dfs(curr, next)) {
59+
return false;
60+
}
61+
}
62+
63+
return true;
64+
}
65+
}

0 commit comments

Comments
 (0)