题解 | #迷宫问题#

迷宫问题

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

本题是常规dfs和bfs常规应用题,要注意的是,需要输出路径的话,最好使用dfs,如果用bfs需要额外定义链表结构来辅助记录路径信息,如果要求最短路径的数量,用bfs最好
import java.io.IOException;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();

        int[][] maze = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                maze[i][j] = scanner.nextInt();
            }
        }

        maze[0][0] = 1;
        List<int[]> curPath = new ArrayList<>();
        curPath.add(new int[]{0, 0});
        dfs(maze, curPath, 0, 0);

        for (int[] step : minPath) {
            System.out.println("(" + step[0] + "," + step[1] + ")");
        }
    }


    static List<int[]> minPath = null;
    static int[][] steps = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    static void dfs(int[][] maze, List<int[]> curPath, int curI, int curJ) {
        if (curI == maze.length - 1 && curJ == maze[0].length - 1) {
            if (minPath == null || minPath.size() > curPath.size()) {
                minPath = new ArrayList<>(curPath);
            }
            return;
        }
        for (int[] nextStep : steps) {
            int nextI = curI + nextStep[0];
            int nextJ = curJ + nextStep[1];
            if (nextI >= 0 && nextJ >= 0
                    && nextI < maze.length && nextJ < maze[0].length
                    && maze[nextI][nextJ] != 1) {
                maze[nextI][nextJ] = 1;
                curPath.add(new int[]{nextI, nextJ});
                dfs(maze, curPath, nextI, nextJ);
                curPath.remove(curPath.size() - 1);
                maze[nextI][nextJ] = 0;
            }
        }
    }
}


全部评论

相关推荐

07-22 13:50
门头沟学院 Java
仁者伍敌:其实能找到就很好了,当然收支能抵
点赞 评论 收藏
分享
06-10 23:36
已编辑
首都经济贸易大学 C++
点赞 评论 收藏
分享
机械打工仔:不管啥专业,找工作改简历的第一课先把你那排版改了,简历上不要写个人简历四个字,找你要简历的谁不知道这个是简历?而且还占那么多空间,直接把自己名字和基础信息写上面,整体字体大一些。 还有这种经典两页简历一页大空白,导出PDF的时候多了一页几乎全是白的你自己看着不难受吗随手的事为啥不能改掉呢,这是态度问题,你试想一下你是HR你打开简历看到格式都没调整过会是什么感受?你自己都不重视你的简历,HR更不会在意。 然后内容你那个做两年咖啡就别往里写了,简历在精不在多,你在往你的简历里打字的时候就要想好这东西对你要找的工作有没有帮助。自我评价写一行就行了,不如给专业技能单开一栏。核心课程均分90这个真别写了,把你上过的有用的专业课列出来也行。有很多地方废话很多的精炼一下,比如你校内项目第一个写的那些,全然没有重点。 好好修改一下,我看你内容也挺优秀的,别被一个随便做的简历耽误了,我一个同专业的打工人看了都揪心更别说一天看几百份简历的HR
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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