多写多想 | #迷宫问题#

迷宫问题

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;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务