Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

797. All Paths From Source to Target #270

Open Tcdian opened 3 years ago

Tcdian commented 3 years ago

797. All Paths From Source to Target

给一个有 n 个结点的有向无环图,找到所有从 0 到 n-1 的路径并输出(不要求按顺序)

二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了a→b你就不能从b→a)空就是没有下一个结点了。

Example

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

Tcdian commented 3 years ago

Solution

/**
 * @param {number[][]} graph
 * @return {number[][]}
 */
var allPathsSourceTarget = function(graph) {
    const result = [];
    const path = [];
    const n = graph.length - 1;
    dfs(0);
    return result;
    function dfs(position) {
        path.push(position);
        if (position === n) {
            result.push([...path]);
        }
        const nextPositions = graph[position];
        for (let i = 0; i < nextPositions.length; i++) {
            dfs(nextPositions[i]);
        }
        path.pop();
    }
};
function allPathsSourceTarget(graph: number[][]): number[][] {
    const result: number[][] = [];
    const path: number[] = [];
    const n = graph.length - 1;
    dfs(0);
    return result;
    function dfs(position: number) {
        path.push(position);
        if (position === n) {
            result.push([...path]);
        }
        const nextPositions = graph[position];
        for (let i = 0; i < nextPositions.length; i++) {
            dfs(nextPositions[i]);
        }
        path.pop();
    }
};