一.题目:
告诉你要修多少门课程,以及这些课程之间的关系,问最终是否能修完所有课程.
Example 1:
Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: 2, [[1,0],[0,1]]
Output: false
Explanation: 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.
二.解题思路:
首先我们可以根据课程之间的关系建立一张图.然后找到所有入度为0的节点(这门课程肯定能修)放入队列.然后,每次排出一个队列元素,首先把它对应的入度列表元素值置为-1,将其邻近的图节点入度-1,若满足节点入度为0则放入队列,最后判断入度列表中是否存在没有更改的元素.
代码如下:
class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
graph = collections.defaultdict(list)
indegrees = [0] * numCourses
for i in prerequisites:
graph[i[1]].append(i[0])
indegrees[i[0]] += 1
queue = collections.deque()
for i in range(numCourses):
if indegrees[i] == 0:
queue.append(i)
while queue:
tmp = queue.pop()
indegrees[tmp] = -1
for j in graph[tmp]:
indegrees[j] -=1
if indegrees[j] == 0:
queue.append(j)
for i in indegrees:
if i != -1:
return False
return True
对于第二题,只需要添加一个result收集每次队列排出的元素即可.
代码如下:
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
graph = collections.defaultdict(list)
indegrees = [0] * numCourses
result = []
for i in prerequisites:
graph[i[1]].append(i[0])
indegrees[i[0]] += 1
queue = collections.deque()
for i in range(numCourses):
if indegrees[i] == 0:
queue.append(i)
while queue:
tmp = queue.pop()
result.append(tmp)
indegrees[tmp] = -1
for j in graph[tmp]:
indegrees[j] -=1
if indegrees[j] == 0:
queue.append(j)
for i in indegrees:
if i != -1:
return []
return result