Acwing 844 走迷宫

题目

给定一个 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

代码与解析

java 复制代码
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;
    }
}
相关推荐
雷渊23 分钟前
深入分析Spring的事务隔离级别及实现原理
java·后端·面试
Smilejudy32 分钟前
不可或缺的相邻引用
后端
惜鸟33 分钟前
Elasticsearch 的字段类型总结
后端
rebel34 分钟前
Java获取excel附件并解析解决方案
java·后端
微客鸟窝36 分钟前
Redis常用数据类型和命令
后端
熊猫片沃子38 分钟前
centos挂载数据盘
后端·centos
微客鸟窝39 分钟前
Redis配置文件解读
后端
不靠谱程序员41 分钟前
"白描APP" OCR 软件 API 逆向抓取
后端·爬虫
小华同学ai42 分钟前
6.4K star!企业级流程引擎黑马,低代码开发竟能如此高效!
后端·github
Paladin_z1 小时前
【导入导出】功能设计方案(Java版)
后端