题解 | 迷宫问题

迷宫问题

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    public static int[][] maze;
    public static Stack<int[]> tempPath = new Stack<>();
    public static Stack<int[]> bestPath = new Stack<>();

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            int m = in.nextInt();
            maze = new int[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    maze[i][j] = in.nextInt();
                }
            }
            tempPath.clear();
            bestPath.clear();

            mazeTrack(0, 0);
            bestPath.forEach(o-> System.out.printf("(%d,%d)%n",o[0], o[1]));
        }
    }

    private static void mazeTrack(int i, int j) {
        maze[i][j] = 1;
        tempPath.push(new int[] {i, j});
        if (i == maze.length - 1 && j == maze[0].length - 1) {//到达终点
            if (bestPath.empty() ||
                    bestPath.size() > tempPath.size()) { // 判斷是否最短路径
                bestPath.addAll(tempPath);
            }
        }

        if (i - 1 >= 0 && maze[i - 1][j] == 0) {// 向上走,没有墙
            mazeTrack(i - 1, j);
        }
        if (i + 1 <= maze.length - 1 && maze[i + 1][j] == 0) {// 向下走,没有墙
            mazeTrack(i + 1, j);
        }
        if (j - 1 >= 0 && maze[i][j - 1] == 0) {// 向左走,没有墙
            mazeTrack(i, j - 1);
        }
        if (j + 1 <= maze[0].length - 1 &&
                maze[i][j + 1] == 0) {// 向右走,没有墙
            mazeTrack(i, j + 1);
        }

        maze[i][j] = 0;
        tempPath.pop();
    }
}

全部评论

相关推荐

04-03 22:41
兰州大学 C++
老六f:有时候是HR发错了,我之前投的百度的后端开发,他给我发的算法工程师,但是确实面的就是百度开发
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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