題目
https://leetcode.com/problems/all-paths-from-source-to-target/
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.
Example:
Input: [[1,2], [3], [3], []]
Output: [[0,1,3],[0,2,3]]
Explanation: The graph looks like this:
0--->1
| |
v v
2--->3
There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
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.
解答
一開始也沒看懂題意,這個二維數組是如何描述這個有向圖。其實是這樣的,二維數組的長度就是節點的個數,比如示例中的長度爲4,所以節點分爲是0, 1, 2, 3。
然而,下一維度描述了,當前第i個節點指向哪個節點。
比如,graph[0]是[1, 2],他的意思是,0號節點指向1,2
class P797_All_Paths_From_Source_to_Target {
// 把結果集弄成靜態變量,省的傳來傳去
static List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<Integer> path = new ArrayList<>();
result.clear();
helper(0, graph, path);
return result;
}
public static void helper(int curr, int[][] graph, List<Integer> path) {
// 將當前節點加入路徑
path.add(curr);
// 查一下當前節點的鄰接表,如果長度爲0,所以到頭了,把這條路徑加入結果集
if (graph[curr].length == 0) {
result.add(path);
} else {
// 如果沒有到頭,那麼查鄰接表,每一個都取出來進行遞歸。
for (int n : graph[curr]) {
// 這裏要注意克隆了一下路徑數組,不然的話,都加到一個裏面去了……
helper(n, graph, clone(path));
}
}
}
public static List<Integer> clone(List<Integer> arr) {
return new ArrayList<>(arr);
}
}