此题想法非常简单,就是用拓扑排序,如果能够排完,则存在一个有序的排列,否则的话就有循环。代码如下:
class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
indegree = [0 for _ in range(numCourses)]
adjacencyMatrix = [[] for _ in range(numCourses)]
queue = []
for a, b in prerequisites:
indegree[a] += 1
adjacencyMatrix[b].append(a)
for i in range(len(indegree)):
if indegree[i] == 0:
queue.append(i)
while queue:
pre = queue.pop(0)
numCourses -= 1
for cur in adjacencyMatrix[pre]:
indegree[cur] -= 1
if indegree[cur]==0:
queue.append(cur)
if numCourses == 0:
return True
else:
return False