Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1089 from agnihotriketan/patch-29
Browse files Browse the repository at this point in the history
Create 261-Graph-Valid-Tree.cs
  • Loading branch information
Ahmad-A0 authored Sep 11, 2022
2 parents b31c233 + fa7688c commit d7dcc9a
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions csharp/261-Graph-Valid-Tree.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}}

0 comments on commit d7dcc9a

Please sign in to comment.