797. All Paths From Source to Target
- All Paths From Source to Target python solution
题目描述
Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order.
The graph is given as follows: the nodes are 0, 1, …, graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.
解析
也需要递归求解,不断寻找对应的索引。终止条件是最后一个节点,比较容易理解
// An highlighted block
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
l=len(graph)
res=[]
def search(nextnode,route):
if nextnode==l-1:
res.append(route+[nextnode])
return
for x in graph[nextnode]:
search(x,route+[nextnode])
search(0,[])
return res
Reference
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/165349/Python-short-solution