2015.5.8 01:26
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 should 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 should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Solution:
This problem is about topological sort. Watch out for multigraph.
Accepted code:
# My code looks ugly enough... class Solution: # @param {integer} numCourses # @param {integer[][]} prerequisites # @return {boolean} def canFinish(self, numCourses, prerequisites): e = prerequisites n = numCourses g = [set() for i in xrange(n)] ind = [0 for i in xrange(n)] ec = len(e) for i in xrange(ec): g[e[i][1]].add(e[i][0]) ec = 0 for i in xrange(n): for j in g[i]: ind[j] += 1 ec += len(g[i]) b = [False for i in xrange(n)] while True: i = 0 while i < n: if ind[i] == 0 and not b[i]: break i += 1 if i == n: break for j in g[i]: ind[j] -= 1 g[i] = set() b[i] = True i = 0 while i < n: if not b[i]: return False i += 1 return True