forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforest000014.java
More file actions
65 lines (53 loc) · 1.53 KB
/
forest000014.java
File metadata and controls
65 lines (53 loc) · 1.53 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
# Time Complexity: O(n)
# Space Complexity: O(n + m)
- m은 edges.length
# Solution
edges[0][0]에서 출발하여 인접한 모든 edge를 DFS로 순회한다.
- cycle이 있는 경우 (이미 방문한 적이 있는 node를 재방문)
- 순회를 마쳤는데 방문하지 않은 node가 있는 경우
위 2경우는 invalid tree이고, 그렇지 않으면 valid tree이다.
*/
class Solution {
public ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
public boolean[] visited;
public boolean validTree(int n, int[][] edges) {
if (edges.length == 0) {
return n == 1;
}
visited = new boolean[n];
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<Integer>());
}
for (int i = 0; i < edges.length; i++) {
int a = edges[i][0];
int b = edges[i][1];
adj.get(a).add(b);
adj.get(b).add(a);
}
if (!dfs(-1, edges[0][0])) {
return false;
}
for (int i = 0; i < n; i++) {
if (!visited[i]) {
return false;
}
}
return true;
}
public boolean dfs(int prev, int curr) {
visited[curr] = true;
for (Integer next : adj.get(curr)) {
if (next == prev) {
continue;
}
if (visited[next]) {
return false;
}
if (!dfs(curr, next)) {
return false;
}
}
return true;
}
}