好几个月没有刷过力扣了,心里十分有罪恶感。
题目:给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
这道题其实是有向无环图的遍历问题,直接可以判断有dfs和bfs两种解法
这道题graph[i][j]代表的是i结点指向j结点。
使用bfs:
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
n = len(graph)
q = deque([[0]]) # q定义为一个存储多个路径的队列
ans = []
while q:
path = q.popleft() # 在q中取出最左边的路径
if path[-1] == n - 1 : # 当路径的最后一个结点为图的最后一个结点则说明遍历完成
ans.append(path)
continue
for nxt in graph[path[-1]]:
q.append(path + [nxt])
return ans
dfs
dfs需要注意的是回溯
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
n = len(graph)
path = [0]
ans = []
def dfs():
if path[-1] == n - 1:
ans.append(list(path))
else:
for nxt in graph[path[-1]]:
path.append(nxt)
dfs()
path.pop()
dfs()
return ans