Skip to content

Commit 3a92455

Browse files
authored
Merge pull request neetcode-gh#1030 from agnihotriketan/patch-9
C# 207-Course-Schedule.cs
2 parents 07b4599 + e744598 commit 3a92455

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

csharp/207-Course-Schedule.cs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
public class Solution {
2+
public bool CanFinish(int numCourses, int[][] prerequisites)
3+
{
4+
5+
IDictionary<int, List<int>> preMap = new Dictionary<int, List<int>>();
6+
HashSet<int> visited = new HashSet<int>();
7+
for (int i = 0; i < numCourses; i++)
8+
{
9+
preMap.Add(i, new List<int>());
10+
}
11+
12+
foreach (int[] course in prerequisites)
13+
{
14+
int courseToTake = course[0];
15+
int courseDependOn = course[1];
16+
preMap[courseToTake].Add(courseDependOn);
17+
}
18+
19+
foreach (int c in Enumerable.Range(0, numCourses))
20+
{
21+
if (!DfsGraph(preMap, visited, c))
22+
{
23+
return false;
24+
}
25+
}
26+
return true;
27+
}
28+
public bool DfsGraph(IDictionary<int, List<int>> preMap, HashSet<int> visited, int crs)
29+
{
30+
if (visited.Contains(crs))
31+
{
32+
return false;
33+
}
34+
if (preMap[crs] == new List<int>())
35+
{
36+
return true;
37+
}
38+
visited.Add(crs);
39+
foreach (var pre in preMap[crs])
40+
{
41+
if (!DfsGraph(preMap, visited, pre))
42+
{
43+
return false;
44+
}
45+
}
46+
visited.Remove(crs);
47+
preMap[crs] = new List<int>();
48+
return true;
49+
}
50+
}

0 commit comments

Comments
 (0)