Course Schedule
2015.5.8 01:26
There is a total of n courses you have to take, labeled from 0 to n - 1 .
Some courses May has 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, are it possible for your to finish all courses?
For example:
2, [[1,0]]
There is a total of 2 courses to take. To take course 1 should has finished course 0. So it is possible.
2, [[1,0],[0,1]]
There is a total of 2 courses to take. To take course 1 should has finished course 0, and to take course 0 you should also has finished course 1. So it is impossible.
Solution:
This problem was about topological sort. Watch out for Multigraph.
Accepted Code:
#My code looks ugly enough ...classSolution:#@param {integer} numcourses #@param {integer[][]} prerequisites #@return {Boolean} defcanfinish (self, numcourses, prerequisites): E=Prerequisites N=numcourses G= [Set () forIinchxrange (N)] Ind= [0 forIinchxrange (N)] EC=Len (e) forIinchxrange (EC): G[e[i][0]].add (e[i][1]) EC=0 forIinchxrange (n): forJinchG[i]: ind[j]+ = 1EC+=Len (g[i]) b= [False forIinchxrange (n)] whiletrue:i=0 whileI <N:ifInd[i] = = 0 and notB[i]: BreakI+ = 1ifi = =N: Break forJinchG[i]: ind[j]-= 1G[i]=set () B[i]=True i=0 whileI <N:if notB[i]:returnFalse i+ = 1returnTrue
Leetcode-course Schedule