标签:
题目描述:public class Solution { public int[] FindOrder(int numCourses, int[,] prerequisites) { var row = prerequisites.GetLength(0); if(row == 0){ int[] c = new int[numCourses]; for(int i=0; i<numCourses; i++){ c[i]=i; } return c; } // save [courseId, refCount] var refCountTable = new int[numCourses]; for(var i = 0;i < row; i++){ refCountTable[prerequisites[i,0]] ++; } // no ref courses var noRefCourses = new Dictionary<int, int>(); for(var i = 0;i < row; i++){ // find courses does not appear in ref table if(refCountTable[prerequisites[i,1]] == 0 && !noRefCourses.ContainsKey(prerequisites[i,1])){ noRefCourses.Add(prerequisites[i,1],1); } } var size = noRefCourses.Count; var result = new int[numCourses]; var count = 0; while(noRefCourses.Count > 0){ var c = noRefCourses.Keys.First(); result[count++] = c; noRefCourses.Remove(c); for(var i = 0;i < row; i++){ if(prerequisites[i,1] == c){ refCountTable[prerequisites[i,0]] --; if(refCountTable[prerequisites[i,0]] == 0 && !noRefCourses.ContainsKey(prerequisites[i,1])){ noRefCourses.Add(prerequisites[i,0], 1); size++; } } } } if(size == numCourses){ return result; } return new int[0]; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode -- Course Schedule II
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/48650023