-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution210.cs
59 lines (51 loc) · 1.59 KB
/
Solution210.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
namespace LeetCode.Solutions;
public class Solution210
{
/// <summary>
/// 210. Course Schedule II - Medium
/// <a href="https://leetcode.com/problems/course-schedule-ii">See the problem</a>
/// </summary>
public int[] FindOrder(int numCourses, int[][] prerequisites)
{
var graph = new Dictionary<int, List<int>>();
var inDegrees = new int[numCourses];
var queue = new Queue<int>();
var result = new List<int>();
// Build the graph
foreach (var prerequisite in prerequisites)
{
if (!graph.ContainsKey(prerequisite[1]))
{
graph[prerequisite[1]] = new List<int>();
}
graph[prerequisite[1]].Add(prerequisite[0]);
inDegrees[prerequisite[0]]++;
}
// Add courses with no prerequisites to the queue
for (var i = 0; i < numCourses; i++)
{
if (inDegrees[i] == 0)
{
queue.Enqueue(i);
}
}
// Topological sort
while (queue.Count > 0)
{
var course = queue.Dequeue();
result.Add(course);
if (graph.ContainsKey(course))
{
foreach (var nextCourse in graph[course])
{
inDegrees[nextCourse]--;
if (inDegrees[nextCourse] == 0)
{
queue.Enqueue(nextCourse);
}
}
}
}
return result.Count == numCourses ? [.. result] : [];
}
}