题解 | #迷宫问题#

迷宫问题

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // while (in.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
        int m = in.nextInt();
        int n = in.nextInt();
        int[][] table = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                table[i][j] = in.nextInt();
            }
        }
        
        ArrayList<Node> path = new ArrayList<>();
        dfs(table, 0, 0, path);
        
        
        for (int i = 0; i < path.size(); i++) {
            System.out.println("(" + path.get(i).x + "," + path.get(i).y + ")");
        }
    }

    private static boolean dfs(int[][] table, int x, int y, List<Node> path) {
        path.add(new Node(x, y));
        table[x][y] = 1;
        int m = table.length;
        int n = table[0].length;

        if (x == m - 1 && y == n - 1) {
            return true;
        }
        if (x + 1 < m && table[x + 1][y] == 0) {
            if (dfs(table, x + 1, y, path)) {
                return true;
            }
            
        }
        if (x - 1 >= 0 && table[x - 1][y] == 0) {
            if (dfs(table, x - 1, y, path)) {
                return true;
            }
        }
        if (y + 1 < n && table[x][y + 1] == 0) {
            if (dfs(table, x, y + 1, path)) {
                return true;
            }
        }
        if (y - 1 >= 0 && table[x][y - 1] == 0) {
            if (dfs(table, x, y - 1, path)) {
                return true;
            }
        }
        path.remove(path.size() - 1);
        
        return false;
    }
}


class Node {
    protected int x;
    protected int y;
    // protected Node father;
    protected Node (int x, int y) {
        this.x = x;
        this.y = y;
        // this.father = father;
    }
}

全部评论

相关推荐

03-11 21:46
西北大学 Java
河和静子:这只是实习工资,我学长北大通班博一的,他同学被这家天天发邮件让他去实习,一个月10w
点赞 评论 收藏
分享
03-05 12:52
吉林大学 Java
挣K存W养DOG:他的价值在于把他家里积攒的财富回馈给社会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务