797. All Paths From Source to Target
solution
# 不判断visited 反而更快, 因为本题输入明确为:有向无环图(DAG)
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
if not graph:
return [[]]
path = [0]
result = []
visited = {}
self.dfs(path, result, graph, visited)
return result
def dfs(self, path, result, graph, visited):
if path[-1] == len(graph) - 1:
result.append(path[:])
return
for i in graph[path[-1]]:
if i not in visited or not visited[i]:
visited[i] = True
path.append(i)
self.dfs(path, result, graph, visited)
path.pop(-1)
visited[i] = Falsefollow up
Last updated