-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCourseSchedule.DFS.20230910.cs
62 lines (57 loc) · 1.56 KB
/
CourseSchedule.DFS.20230910.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
51
52
53
54
55
56
57
58
59
60
61
62
public class Solution
{
public bool CanFinish(int numCourses, int[][] prerequisites)
{
var coursesAdjacencyHashMap = new Dictionary<int, List<int>>();
foreach (var courses in prerequisites)
{
if (coursesAdjacencyHashMap.ContainsKey(courses[0]))
{
coursesAdjacencyHashMap[courses[0]].Add(courses[1]);
}
else
{
coursesAdjacencyHashMap.Add(courses[0], new List<int> { courses[1] });
}
}
Stack<int> stack = new Stack<int>();
HashSet<int> visited = new HashSet<int>();
HashSet<int> visiting = new HashSet<int>();
for (int i = 0; i < numCourses; i++)
{
if (!visited.Contains(i))
{
stack.Push(i);
while (stack.Count > 0)
{
int node = stack.Peek(); // peek but don't remove yet
visiting.Add(node);
bool hasUnvisitedNeighbor = false;
if (coursesAdjacencyHashMap.ContainsKey(node))
{
foreach (var req in coursesAdjacencyHashMap[node])
{
if (visiting.Contains(req))
{
return false; // cycle detected
}
if (!visited.Contains(req))
{
stack.Push(req);
hasUnvisitedNeighbor = true;
break;
}
}
}
if (!hasUnvisitedNeighbor)
{
stack.Pop(); // no unvisited neighbors, we're done with this node
visiting.Remove(node);
visited.Add(node);
}
}
}
}
return true;
}
}