LeetCode 797
要求的是所有的path,所以简单的dfs就可以实现。
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
if len(graph) == 0: return []
result = []
currentPath = [0]
end = len(graph)-1
def dfs(currentPath, graph, result, end):
if currentPath[-1] == end:
result.append(currentPath.copy())
return
for i in graph[currentPath[-1]]:
currentPath.append(i)
dfs(currentPath, graph, result, end)
currentPath.pop()
dfs(currentPath, graph, result, end)
return result