题解 | #迷宫问题#

迷宫问题

https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc?tpId=37&tqId=21266&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=

import java.util.Scanner;
import java.util.Scanner;
import java.util.Stack;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            int map[][] = new int[x][y];
            for (int i = 0; i < x; i++) {
                for (int j = 0; j < y; j++) {
                    map[i][j] = scanner.nextInt();
                }
            }

            Stack<MazeVO> stack = new Stack();
            getMaze(map, 0, 0, stack);

            for (MazeVO mazeVO : stack) {
                System.out.println("(" + mazeVO.x + "," + mazeVO.y + ")");
            }
        }

    }

    public static boolean getMaze(int map[][], int x, int y, Stack<MazeVO> stack) {
        MazeVO mazeVO = new MazeVO(x, y);
        stack.add(mazeVO);// 放入栈
        map[x][y] = 1;
        // 结束条件
        if (x == map.length - 1 && y == map[0].length - 1) {
            return true;
        }
        // 向右走
        if (y < map[0].length - 1 && map[x][y + 1] == 0) {
            if (getMaze(map, x, y + 1, stack)) {
                return true;
            }
        }

        // 向左走
        if (y > 0 && map[x][y - 1] == 0) {
            if (getMaze(map, x, y - 1, stack)) {
                return true;
            }
        }

        // 向下走
        if (x < map.length - 1 && map[x + 1][y] == 0) {
            if (getMaze(map, x + 1, y, stack)) {
                return true;
            }
        }

        // 向上走
        if (x > 0 && map[x - 1][y] == 0) {
            if (getMaze(map, x - 1, y, stack)) {
                return true;
            }
        }

        stack.pop();// 如果都不满足,弹出
        map[x][y] = 0;
        return false;
    }


}

class MazeVO {
    int x;
    int y;

    public MazeVO(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

全部评论

相关推荐

把球:这个听过,你加了就会发现是字节的hr
点赞 评论 收藏
分享
10-05 23:02
东北大学 Java
我说句实话啊:那时候看三个月培训班视频,随便做个项目背点八股,都能说3 40w是侮辱价
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务