【牛客網】迷宮問題

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

採用搜索回溯的方法。

import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int row = in.nextInt();
            int column = in.nextInt();
            int[][] arr = new int[row][column];
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < column; j++) {
                    arr[i][j] = in.nextInt();
                }
            }
            boolean[][] mark = new boolean[row][column];
            LinkedList<int[]> path = new LinkedList<>();
            shortPath = new LinkedList<>();
            shortPath.add(new int[]{6, 6});
            path.add(new int[]{0, 0});
            leastStep = Integer.MAX_VALUE;
            mark[0][0] = true;
            dfs(arr, mark, 0, 0, path, row, column);
            for (int[] ints : shortPath) {
                System.out.println("(" + ints[0] + "," + ints[1] + ")");
            }
        }
    }

    public static int leastStep;
    public static LinkedList<int[]> shortPath;

    /**
     * @param arr    迷宮
     * @param mark   標記是否走過
     * @param i      橫座標
     * @param j      縱座標
     * @param path   路徑
     * @param row    迷宮的行數
     * @param column 迷宮的列數
     */
    private static void dfs(int[][] arr,
                            boolean[][] mark,
                            int i,
                            int j,
                            LinkedList<int[]> path,
                            int row,
                            int column) {

        if (i == row - 1 && j == column - 1) {
            // 到出口了。
            if (path.size() < leastStep) {
                shortPath = new LinkedList<>(path);// 如果這個路徑比較短的話,保存。
                leastStep = path.size();
            }
            return;
        }

        // 進行遍歷。四個方向。
        int[][] move = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

        for (int k = 0; k < 4; k++) {

            int x = i + move[k][0];
            int y = j + move[k][1];

            if (x < 0 || x >= row || y < 0 || y >= column) {
                continue;
            }

            if (mark[x][y]) { // 說明走過了
                continue;
            }

            // 說明在合理的範圍中,並且這個位置沒有走過。
            if (arr[x][y] == 1) { // 說明是牆
                continue;
            }

            // 這個位置不是牆。還在合理的範圍,還沒走過。
            mark[x][y] = true;

            path.add(new int[]{x, y}); // path中添加這個座標

            dfs(arr, mark, x, y, path, row, column);

            path.removeLast();
            mark[x][y] = false;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章