Acwing 844 走迷宫

2024-01-10 10:47:08

题目

给定一个 n×m 的二维整数数组,用来表示一个迷宫,数组中只包含 00 或 11,其中 00 表示可以走的路,11 表示不可通过的墙壁。

最初,有一个人位于左上角 (1,1)(1,1) 处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。

请问,该人从左上角移动至右下角 (n,m) 处,至少需要移动多少次。

数据保证 (1,1)(1,1) 处和 (n,m) 处的数字为 0,0,且一定至少存在一条通路。

输入格式

第一行包含两个整数 n 和 m。

接下来 n 行,每行包含 m 个整数(00 或 11),表示完整的二维数组迷宫。

输出格式

输出一个整数,表示从左上角移动至右下角的最少移动次数。

数据范围

1≤n,m≤1001≤100

输入样例:
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
输出样例:
8

代码与解析

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

public class Main {

    private static final int N = 110;
    private static int[][] g = new int[N][N], d = new int[N][N];
    private static PII[] q = new PII[N * N];
    private static int n;
    private static int m;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 读取输入的 n 和 m
        n = scanner.nextInt();
        m = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        // 读取迷宫数据并存入 g 数组
        for (int i = 0; i < n; i++) {
            String[] str = scanner.nextLine().split(" ");
            for (int j = 0; j < m; j++) {
                g[i][j] = Integer.parseInt(str[j]);
            }
        }

        System.out.println(bfs()); // 调用 bfs 方法计算最短路径
        scanner.close();
    }

    private static int bfs() {
        int hh = 0, tt = 0;
        q[0] = new PII(0, 0); // 初始化队列,起点为 (0, 0)
        for (int i = 0; i < d.length; i++) {
            for (int j = 0; j < d[i].length; j++) {
                d[j][i] = -1; // 初始化距离数组为 -1,表示未访问过
            }
        }
        d[0][0] = 0; // 起点到起点的距离为 0

        int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1}; // 上右下左四个方向
        while (hh <= tt) {
            PII t = q[hh++];
            for (int i = 0; i < 4; i++) {
                int x = t.getFirst() + dx[i], y = t.getSecond() + dy[i]; // 计算当前位置移动后的位置
                if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1) {
                    d[x][y] = d[t.getFirst()][t.getSecond()] + 1; // 更新到达新位置的距离
                    q[++tt] = new PII(x, y); // 将可到达的新位置加入队列
                }
            }
        }
        return d[n - 1][m - 1]; // 返回右下角的最短路径长度
    }

}

class PII {
    private int first;
    private int second;

    public PII(int first, int second) {
        this.first = first;
        this.second = second;
    }

    public PII() {

    }

    public int getFirst() {
        return first;
    }

    public int getSecond() {
        return second;
    }
}

文章来源:https://blog.csdn.net/m0_51547272/article/details/135454204
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。