forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0207-course-schedule.cs
50 lines (47 loc) · 1.46 KB
/
0207-course-schedule.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
42
43
44
45
46
47
48
49
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;
}
}