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;
}
}
文章版权声明:除非注明,否则均为彭超的博客原创文章,转载或复制请以超链接形式并注明出处。
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。