797. All Paths From Source to Target 從來源到目標的所有路徑
❀ Origin
Problem
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.
Note
- The number of nodes in the graph will be in the range [2, 15].
- You can print different paths in any order, but you should keep the order of nodes inside one path.
Example 1
1 | Input: [[1,2], [3], [3], []] |
❀ 翻譯
問題
給定有N
個節點的有向無環圖.
找出所有從節點0
到節點N-1
的可行路徑, 並將它們找順序排列後回傳.
給定的圖表如下:
節點的值會是 0, 1, …, graph.length - 1.
graph[i] 代表的是邊線 edge (i, j)上所有存在的 nodes j 的列表.
注意
- 圖中的節點的數量範圍將會在 [2, 15]
- 你可以用任何順序去印出不同的路徑, 但你應該保持節點在一個路徑內的順序.
❀ Solution
參考
Idea
底子太差, 一開始不會 DFS ( Depth-First Search 深度優先搜尋 ),
莫名其妙寫出來的, 忙完必須回頭確實弄懂.
主概念是遍歷所有點, 並判斷是否為目標值後組成回傳陣列.
網路大神前輩說此題是典型 DFS + Backtracking 的題目
JavaScript
1 | /** |
Execution
1 | Input: [[1, 2, 3], [4], [], [4], []] |