forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0261-graph-valid-tree.cs
41 lines (35 loc) · 1.12 KB
/
0261-graph-valid-tree.cs
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
public class Solution {
public bool ValidTree(int n, int[][] edges)
{
if (n == 0) return true;
var adj = new HashSet<int>[n];
for (int i = 0; i < n; i++)
{
adj[i] = new HashSet<int>();
}
foreach (var edge in edges)
{
var e1 = edge[0];
var e2 = edge[1];
adj[e1].Add(e2); adj[e2].Add(e1);
}
var visited = new bool[n];
var res = DfsValidTree(adj, 0, visited);
if (visited.Any(c => !c)) return false;
return res;
}
private bool DfsValidTree(HashSet<int>[] adj, int current, bool[] visited)
{
if (visited[current]) return false;
visited[current] = true;
var nextLevel = adj[current];
foreach (var level in nextLevel)
{
adj[level].Remove(current);
if (!DfsValidTree(adj, level, visited))
{
return false;
}
}
return true;
}}