There are a total of n courses you have to take, labeled from 0
to n - 1
.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]
. Another correct ordering is[0,2,1,3]
.
Note:
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
1 public class Solution { 2 public int[] FindOrder(int numCourses, int[,] prerequisites) { 3 var dependencies = new List<int>[numCourses]; 4 5 for (int i = 0; i < prerequisites.GetLength(0); i++) 6 { 7 int c = prerequisites[i, 0], d = prerequisites[i, 1]; 8 9 if (dependencies[c] == null) dependencies[c] = new List<int>(); 10 11 dependencies[c].Add(d); 12 } 13 14 var result = new List<int>(); 15 16 var done = new bool[numCourses]; 17 18 for (int i = 0; i < numCourses; i++) 19 { 20 if (!DFS(new bool[numCourses], done, dependencies, i, result)) 21 { 22 return new int[] {}; 23 } 24 } 25 26 return result.ToArray(); 27 } 28 29 private bool DFS(bool[] visited, bool[] done, List<int>[] dependencies, int c, List<int> result) 30 { 31 if (done[c]) return true; 32 if (visited[c]) return false; 33 34 visited[c] = true; 35 36 if (dependencies[c] != null) 37 { 38 foreach (var d in dependencies[c]) 39 { 40 if (!DFS(visited, done, dependencies, d, result)) return false; 41 } 42 } 43 44 result.Add(c); 45 done[c] = true; 46 return true; 47 } 48 49 }