多写多想 | #迷宫问题#

迷宫问题

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter("\n");
        while (scanner.hasNext()){
            String next = scanner.next();
            int i = Integer.parseInt(next.split(" ")[0]);
            int j = Integer.parseInt(next.split(" ")[1]);
            int[][] dp = new int[i][j];
            for (int k = 0; k < i; k++) {
                String[] rows = scanner.next().split(" ");
                for (int l = 0; l < rows.length; l++) {
                    dp[k][l] = Integer.parseInt(rows[l]);
                }
            }
            LinkedList<String> list = new LinkedList<>();
            dfs(dp, i, j, 0, 0, list, new boolean[i+1][j+1]);
            while (!list.isEmpty()) System.out.println(list.pop());
        }
    }


    public static boolean dfs(int[][] original, int i, int j, int row, int column, LinkedList<String> list, boolean[][] can) {
        can[row][column] = true;
        if ((row==i-1&&column==j-1)) {
            list.push("(" + row + "," + column + ")");
            return true;
        }

        //向上
        if (row-1>=0 && !can[row-1][column] && original[row-1][column] == 0) {
            if (dfs(original, i, j, row-1, column, list, can)) {
                list.push("(" + row + "," + column + ")");
                return true;
            }
        }

        //向下
        if (row+1<i && !can[row+1][column] && original[row+1][column] == 0) {
            if (dfs(original, i, j, row + 1, column, list, can)) {
                list.push("(" + row + "," + column + ")");
                return true;
            }
        }
        
        //向右
        if (column+1<j && !can[row][column+1] && original[row][column+1] == 0) {
            if (dfs(original, i, j, row, column+1, list, can)) {
                list.push("(" + row + "," + column + ")");
                return true;
            }
        }
        //向左
        if (column-1>=0 && !can[row][column-1] && original[row][column-1] == 0) {
            if (dfs(original, i, j, row, column-1, list, can)) {
                list.push("(" + row + "," + column + ")");
                return true;
            }
        }
        return false;
    }
}

全部评论

相关推荐

Noob1024:一笔传三代,人走笔还在
点赞 评论 收藏
分享
ArisRobert:统一解释一下,第4点的意思是,公司按需通知员工,没被通知到的员工是没法去上班的,所以只要没被通知到,就自动离职。就是一种比较抽象的裁员。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务