题解 | #迷宫问题#

迷宫问题

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static class Node {
        int x;
        int y;
        public Node(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            int m = in.nextInt();
            int[][] arr = new int[n][m];

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    arr[i][j] = in.nextInt();
                }
            }
            List<Node> list = new ArrayList<>();
            List<Node> minList = new ArrayList<>();
            boolean[][] isSame = new boolean[n][m];

            migong(list, minList, 0, 0, arr, isSame);
            for (Node node : minList) {
                System.out.println("("+node.x+","+node.y+")");
            }

        }
    }

    public static void migong(List<Node> list, List<Node> minList, int x,
    int y, int[][] arr, boolean[][] isSame) {
        if (x < 0 || x >= arr.length || y < 0 || y >= arr[0].length || 
        isSame[x][y] == true || arr[x][y] == 1) {
            return;
        }

        Node node = new Node(x, y);
        list.add(node);
        isSame[x][y] = true;
        if (x == arr.length-1 && y == arr[0].length-1) {
            if (minList.isEmpty() || minList.size() > list.size()) {
                minList.addAll(list);
            }
            list.remove(list.size()-1);
            isSame[x][y] = false;
            return;
        }
        migong(list, minList, x+1, y, arr, isSame);
        migong(list, minList, x-1, y, arr, isSame);
        migong(list, minList, x, y+1, arr, isSame);
        migong(list, minList, x, y-1, arr, isSame);
        list.remove(list.size()-1);
        isSame[x][y] = false;
    }
}

全部评论

相关推荐

Cherrycola01:0实习 0项目 约等于啥也没有啊 哥们儿这简历认真的吗
点赞 评论 收藏
分享
03-30 21:02
已编辑
武汉大学 Java
ALEX_BLX:虽然说聊天记录不可信,不过这个趋势确实如此但我觉得也要想到一点就是卷后端的人里真正有“料”的人又有多少,我说的这个料都不是说一定要到大佬那种级别,而是就一个正常的水平。即使是现在也有很多人是跟风转码的,2-3个月速成后端技术栈的人数不胜数,但今时不同往日没可能靠速成进大厂了。这种情况就跟考研一样,你能上考场就已经打败一半的人了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务