目 录CONTENT

文章目录

844. 走迷宫

Gz
Gz
2022-07-04 / 0 评论 / 0 点赞 / 386 阅读 / 1,227 字 / 正在检测是否收录...

844. 走迷宫

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

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

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

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

输入格式

第一行包含两个整数 nn 和 mm。

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

输出格式

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

数据范围

1≤n,m≤1001≤n,m≤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 {
    static int N = 110;
    static int[][] g = new int[N][N];
    static int[][] d = new int[N][N];
    public static int bfs(int n, int m){
        Queue<int[]> queue = new LinkedList<>();
        d[0][0] = 0;
        int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0 ,-1};
        queue.add(new int[]{0, 0});
        //如果队列不为空
        while(!queue.isEmpty()){
            //取出队头
            int a[] = queue.remove();
            //判断上下左右
            for (int i = 0; i < 4; i++) {
                //上下左右值
                int x = a[0] + dx[i], y = a[1] + dy[i];
                //判断是否走得通
                if (x >= 0 && x < n && y >= 0 && y < m && d[x][y] == 0 && g[x][y] == 0){
                    //下一步等于上一步值+1
                    d[x][y] = d[a[0]][a[1]] + 1;
                    //再将这个这个值为添加到队列继续bfs
                    queue.add(new int[]{x,y});
                }
            }
        }
        return d[n-1][m-1];
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                g[i][j] = scanner.nextInt();
            }
        }
        System.out.println(bfs(n, m));
    }
}
0

评论区