LeetCode -- Course Schedule
Description:
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, is it possible for you to finish all courses?
For example:
2, [[1, 0]
There are a total of 2 courses to take. To take course 1 you shoshould have finished course 0. So it is possible.
2, [[1, 0], [0, 1]
There are a total of 2 courses to take. To take course 1 you shoshould have finished course 0, and to take course 0 you shoshould also have finished course 1. So it is impossible.
For Course Selection questions, you need to select n courses. The known dependencies are two-dimensional arrays [{}, {}, {x, y}...], 0 indicates that the course 0 depends on course 1 (you must first select 1 if you want to select 0), course 0 depends on course 2, and course x depends on course y. The value range of the course id is [0, n ).
Ideas:
Each course is regarded as a node, and the dependency array is actually a graph structure. For the dependent array [{0, 1}, {2, 3}], it is actually equivalent to 0-> 1, 2-> 3 in the figure. As long as there is no ring, the course selection operation can continue.
1. Use referencing [0... n-1] to store the number of other courses on which the current course depends
2. Use the marker array selections [0... n-1] to mark whether the course selections [I] has been selected
3. traverse the referencing array each time to find the courses with zero dependencies and which are not yet selected. These course IDs will be selected and put into the set S; then traverse S, find who depends on S [I] in the dependency graph, get the course id: course, and then update the reference array: referencing [course] --. Repeat Step 1.
4. until there is no element 0 in referencing or n courses are selected.
Implementation Code:
public class Solution { public bool CanFinish(int numCourses, int[,] prerequisites) { var row = prerequisites.GetLength(0); if(row < 2){ return true; } var referencing = new int[numCourses]; var selections = new bool[numCourses]; for(var i = 0;i < row; i++) { referencing[prerequisites[i,0]] ++; } var c = 0; while(c < numCourses){ // find out which courses not referencing others var selected = new List
(); for(var i = 0;i < referencing.Length; i++){ if(referencing[i] == 0 && !selections[i]) { // select this course c++; selections[i] = true; selected.Add(i); } } if(selected.Count == 0) { break; } // find out which ones referencing this course then update referencing counter foreach(var s in selected){ for(var j = 0; j < row; j++){ if(prerequisites[j,1] == s){ referencing[prerequisites[j,0]] --; } } } } return c >= numCourses; }}