leetcode 797. All Paths From Source to Target | 797. 所有可能的路径(回溯法)

x33g5p2x  于2021-11-28 转载在 其他  
字(0.9k)|赞(0)|评价(0)|浏览(173)

题目

https://leetcode.com/problems/all-paths-from-source-to-target/

题解

回溯,中规中矩,直接上代码。

class Solution {
    int N;

    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        N = graph.length;
        boolean[][] g = new boolean[N][N];
        for (int i = 0; i < N; i++) {
            for (int j : graph[i]) {
                g[i][j] = true;
            }
        }
        return process(g, 0, new HashSet<>());
    }

    // 从 i 出发,到达 n-1 的全部路径
    public List<List<Integer>> process(boolean[][] g, int i, Set<Integer> seen) {
        List<List<Integer>> result = new ArrayList<>();

        if (i == N - 1) { // 已到终点
            result.add(new ArrayList<>());
            result.get(0).add(N - 1);
            return result;
        } else { // 未到终点
            for (int j = 0; j < N; j++) { // i -> j -> N-1
                if (g[i][j] && !seen.contains(j)) {
                    // backtracing
                    seen.add(j);
                    for (List<Integer> path : process(g, j, seen)) {
                        List<Integer> list = new ArrayList<>();
                        list.add(i);
                        list.addAll(path);
                        result.add(list);
                    }
                    seen.remove(j);
                }
            }
        }
        return result;
    }
}

相关文章

微信公众号

最新文章

更多