Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1030 from agnihotriketan/patch-9
Browse files Browse the repository at this point in the history
C# 207-Course-Schedule.cs
  • Loading branch information
Ahmad-A0 authored Sep 5, 2022
2 parents 07b4599 + e744598 commit 3a92455
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions csharp/207-Course-Schedule.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
public class Solution {
public bool CanFinish(int numCourses, int[][] prerequisites)
{

IDictionary<int, List<int>> preMap = new Dictionary<int, List<int>>();
HashSet<int> visited = new HashSet<int>();
for (int i = 0; i < numCourses; i++)
{
preMap.Add(i, new List<int>());
}

foreach (int[] course in prerequisites)
{
int courseToTake = course[0];
int courseDependOn = course[1];
preMap[courseToTake].Add(courseDependOn);
}

foreach (int c in Enumerable.Range(0, numCourses))
{
if (!DfsGraph(preMap, visited, c))
{
return false;
}
}
return true;
}
public bool DfsGraph(IDictionary<int, List<int>> preMap, HashSet<int> visited, int crs)
{
if (visited.Contains(crs))
{
return false;
}
if (preMap[crs] == new List<int>())
{
return true;
}
visited.Add(crs);
foreach (var pre in preMap[crs])
{
if (!DfsGraph(preMap, visited, pre))
{
return false;
}
}
visited.Remove(crs);
preMap[crs] = new List<int>();
return true;
}
}

0 comments on commit 3a92455

Please sign in to comment.