边工作边刷题:70天一遍leetcode: day 25
Course Schedule I/II
要点:
- 有向图的topological sort,indegree方法需要图结构吗?需要,因为每层遍历是根据图得到连接关系更新indegree的
- 图的dfs方法,虽然可以在recursion call之前或者之后更新visited,但是最好统一,这样不会出错。对这题,
- visited在call外判断,call内更新,
- recStk在call内开始进,call内结束出
- 注意res在call内结束入(因为深层的排前面),不pop
错误点:
- 一个非常tricky的错误是对邻接点先检查visited,然后检查是否在recStk。实际上如果有环,肯定另一端已经visited了,这样不会返回false,正确的方法应该先检查是否在recStk里
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
def dfs(graph, i, recStk, visited, res):
visited[i]=True
recStk.add(i)
for p in graph[i]:
if p in recStk:
return False
elif not visited[p]:
if not dfs(graph, p, recStk, visited, res):
return False
recStk.remove(i)
res.append(i)
return True
graph = [[] for i in range(numCourses)]
for e in prerequisites:
graph[e[0]].append(e[1])
res = []
recStk = set()
visited = [False]*numCourses
for p in range(numCourses):
if not visited[p]:
if not dfs(graph, p, recStk, visited, res):
return []
# res.reverse()
return res