-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path261. Graph Valid Tree.java
More file actions
38 lines (36 loc) · 1.15 KB
/
261. Graph Valid Tree.java
File metadata and controls
38 lines (36 loc) · 1.15 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
public class Solution {
public boolean validTree(int n, int[][] edges) {
int[] visited = new int[n];
List<List<Integer>> adjList = new ArrayList<>();
for (int i=0; i<n; ++i) { adjList.add(new ArrayList<Integer>()); }
for (int[] edge: edges) {
adjList.get(edge[0]).add(edge[1]);
adjList.get(edge[1]).add(edge[0]);
}
if(hasCycle(-1, 0, visited, adjList)){
return false;
}
for(int i=0;i<visited.length;i++){
if(visited[i] == 0){
return false;
}
}
return true;
}
boolean hasCycle(int pred, int cur, int[] visited, List<List<Integer>> adjList){
visited[cur] = 1;
for(Integer x : adjList.get(cur)){
if(x == pred) continue;
if(visited[x] == 1){
return true;
}
else if(visited[x] == 0){
if(hasCycle(cur, x, visited, adjList)){
return true;
}
}
}
//visited[cur] = 2;
return false;
}
}