题解 | #迷宫问题#

迷宫问题

https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

import java.util.*;

// 如有一味绝境,非历十方生死
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            m = in.nextInt();
            n = in.nextInt();
            int[][] gird = new int[m][n];
            for(int y = 0; y < m; y++) {
                for(int x = 0; x < n; x++) {
                    gird[y][x] = in.nextInt();
                }
            }
            f(gird);
            for(int[] p : list) {
                 System.out.println("("+p[0] + "," + p[1] + ")");
            }
        }
    }

    public static List<int[]> f(int[][] gird) {
        list.clear();
        boolean[][] vis = new boolean[m][n];
        step(gird, vis, 0, 0, new ArrayList<int[]>());
        return list;
    }

    public static void step(int[][] gird, boolean[][] vis, int y, int x, List<int[]> cur) {
        if(y < 0 || y >= m || x < 0 || x >= n || vis[y][x] || gird[y][x] == 1) {
            return;
        }
        if(y == m-1 && x == n-1) {
            cur.add(new int[]{y, x});
            if(list.size() == 0 || cur.size() < list.size()) {
                list = new ArrayList<int[]>(cur);
            }
            cur.remove(cur.size()-1);
            return;
        }
        vis[y][x] = true;
        cur.add(new int[]{y,x});
        for(int i = 0; i < 4; i++) {
            int ny = y + dir[i][0], nx = x + dir[i][1];
            step(gird, vis, ny, nx, cur);
        }
        vis[y][x] = false;
        cur.remove(cur.size()-1);
    }

    static int m, n;
    static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}};
    static List<int[]> list = new ArrayList<>();
}

全部评论

相关推荐

头像
昨天 14:20
已编辑
门头沟学院 Java
之前在学校的时候,舍友老是熬夜打游戏,周末还喜欢早起打游戏😅,吵得没法睡到自然醒现在出来实习独居后,想干嘛就干嘛,打游戏刷视频,没有任何顾虑,学习工作,也没有人能打扰我🦌就这个独居爽
天才无敌小土豆:之前在学校 宿舍一个巨瘦的哥们天天熬夜打游戏 呼噜声还巨大 我睡觉超级敏感 天天睡不着 我睡他下铺 半夜踹他床板让他飞起来 就那一会不会打呼噜 然后继续 那段时间我感觉我都yw了 后来我换了个远一点的床铺 买了新的那种可以捏小的耳塞 老子睡觉爽死了 后悔大三才发现这种耳塞 老子yw又好了 天天夜里上厕所都梆硬
独居后,你的生活是更好了...
点赞 评论 收藏
分享
07-30 23:39
门头沟学院 Java
kulua:虾皮最后疯狂补录,完全不用担心
点赞 评论 收藏
分享
牛客37328580...:个人感觉项目只是列出来了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务