力扣算法之《797. 所有可能的路径》

这篇博客详细介绍了LeetCode算法题797,讨论了如何找出一个m x n网格中所有可能的行走路径。通过深度优先搜索(DFS)策略,用Java实现了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[力扣算法]《797. 所有可能的路径》

class Solution {
    // follow the solution from the official website of leetcode
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    Deque<Integer> stack = new ArrayDeque<Integer>();
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        // if(graph == null || graph.length == 0)return new
        stack.offerLast(0);
        int n = graph.length;
        dfs(graph, 0, n-1);
        return ans;
    }
    
    
    public void dfs(int[][]g, int n, int m){
        if(n == m){
            ans.add(new ArrayList<Integer>(stack));
            return;
        }
        for(int i : g[n]){
            stack.offerLast(i);
            dfs(g, i, m);
            // dfs(g, i, n); // error 2: parameter error use results
            // dfs(i, n);  // error 1: parameter error use result
            stack.pollLast();
        }
        // stack.pollLast();  // error 3: place error
    }
    // follow the solution from the official website of leetcode
    
    
    
    
//     public List<List<Integer>> allPathsSourceTarget(int[][] graph) {  // the 1st try: failed
//         // if(graph.length == 0)return new List(){};
//         // int n = graph.length;
//         // int[][] tar = new int[n][n];
//         // for(int i = 0; i < n; ++i){
//         //     int m = graph[i].length;
//         //     for(int j = 0; j < m; ++j){
//         //         int k = graph[i][j];
//         //         tar[i][k] = 1;
//         //     }
//         // }
//         // int[] visited = new int[len];
//         // List<List<Integer>> l = new ArrayList<List<Integer>>();
//         // for(int i = 0; i< n; ++i){
//         //     for(int j = 0; j < m; ++j){
//         //         if(graph[i][j] == 1){
//         //             wfs(l, graph, visited, i, j);
//         //         }
//         //     }
//         // }
        
//     }
    
//     public void static wfs(List<List<Integer>> l,int[][] g, boolean[] visited, int r, int c){
//         int len = g.length;
//         List<Integer> list;
//         if(r<0 || r>=len || c<0 || c>=len || visited[c]==true || g[r][c]==0)return;
//         visited[j] = true;
//         list = new ArrayList<Integer>();
//         list.add(j);
//         g[c][r] = 0;
//         wfs(l, g, visited, c, )
//     }
    // the 1st try: failed
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值