Java 求走迷宫的最小步数(bfs)

 使用bfs可以求走迷宫从起始点到目标点的最小步数和路径。

题目

 题目链接811.走迷宫
题目:
给定一个 n×m 的二维整数数组,用来表示一个迷宫,数组中只包含 0 或 1,其中 0 表示可以走的路,1 表示不可通过的墙壁。

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

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

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

输入格式
第一行包含两个整数 n 和 m。

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

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

数据范围
1≤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

题解

&emps;使用队列来宽度优先搜索,每次取出队首,寻找队首周围可以走的点,加入队列,记录起始点到达该点的步数。第一次到达目标点即为最小步数

代码

import java.util.*;
public class Main{
    static int N = 110;
    static int g[][] = new int[N][N];
    static int d[][] = new int[N][N];
    static int n ;
    static int m ;
    static int dfs(){
        LinkedList<PII> queue = new LinkedList<PII>();
        queue.add( new PII(0,0) );
        for(int i = 0 ;i<n;i++){
            Arrays.fill(d[i],-1 );
        }
        d[0][0] = 0;
        int dx[] = {-1,0,1,0};
        int dy[] = {0,1,0,-1};
        while( ! queue.isEmpty()  ){
            PII t = queue.poll();
            for(int i =0 ;i<4;i++){
                int x = t.x+dx[i];
                int y = t.y+dy[i];
                if(x>= 0&& x<n && y>=0&&y<m&& g[x][y]==0 &&d[x][y]==-1 ){
                    d[x][y] = d[t.x][t.y] +1;
                    queue.add(new PII(x,y) );
                }
                
            }
        }
        return d[n-1][m-1];
    }
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        for(int i = 0;i<n;i++){
            for(int j = 0;j<m;j++){
                g[i][j] = sc.nextInt();
            }
        }
        int t = dfs();
        System.out.println(t);
    }
}
class PII{
    
    int x;
    int y ;
    PII(int x,int y){
        this.x = x;
        this.y = y;
    }
    
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tanxinji

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值