797. 所有可能的路径
代码一:DFS回溯
class Solution(object):
# 方法一:DFS
def allPathsSourceTarget(self, graph):
"""
:type graph: List[List[int]]
:rtype: List[List[int]]
"""
if not graph[0]:
return []
res = []
n = len(graph)
self.dfs(graph, 0, n - 1, [0], res)
return res
def dfs(self, graph, cur, end, temp, res):
# 递归出口:当前节点是n-1时,说明找到一条新路径
if temp[-1] == end:
res.append(temp)
return
# 顺着当前节点往下走
for i in graph[cur]:
self.dfs(graph, i, end, temp + [i], res)
代码二:BFS
class Solution(object):
def allPathsSourceTarget(self, graph):
"""
:type graph: List[List[int]]
:rtype: List[List[int]]
"""
# 特判
if not graph[0]:
return []
# 路径终点
end = len(graph) - 1
res = []
# 队列初始化
nodeQueue = [0]
pathQueue = [[0]]
while nodeQueue:
node = nodeQueue.pop(0)
path = pathQueue.pop(0)
# 遍历当前节点能达到的所有节点
for i in graph[node]:
# 若当前节点是终点,则找到一条新路径
if i == end:
res.append(path + [i])
# 否则,当前节点先入队,并更新当前路径
else:
nodeQueue.append(i)
pathQueue.append(path + [i])
return res