给定一个n*m的二维整数数组,用来表示一个迷宫,数组中只包含0或1,其中0表示可以走的路,1表示不可通过的墙壁。
最初,有一个人位于左上角(1, 1)处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。
请问,该人从左上角移动至右下角(n, m)处,至少需要移动多少次。
数据保证(1, 1)处和(n, m)处的数字为0,且一定至少存在一条通路。
输入格式
第一行包含两个整数n和m。
接下来n行,每行包含m个整数(0或1),表示完整的二维数组迷宫。
输出格式
输出一个整数,表示从左上角移动至右下角的最少移动次数。
数据范围
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.io.*;
import java.lang.*;
import java.util.*;
class Pair{
Integer first;
Integer second;
public Pair(Integer first, Integer second){
this.first = first;
this.second = second;
}
}
class Main{
static int n = 0, m = 0;
static int N = 110;
static int[][] s = new int[N][N];//存储迷宫
static Pair[] q = new Pair[N * N]; //队列
static int[] dx = {0, -1, 0, 1};//方向向量
static int[] dy = {-1, 0, 1, 0};
static int[][] d = new int[N][N];//距离
static void bfs(){
int hh = 0, tt = 0;
for(int i = 1; i <= n; ++i)
Arrays.fill(d[i], -1);
q[0] = new Pair(1, 1);
d[1][1] = 0;
while(hh <= tt){
Pair p = q[hh++];
for(int i = 0; i < 4; ++i){
int x = p.first + dx[i];
int y = p.second + dy[i];
if(x >= 1 && x <= n && y >= 1 && y <= m && s[x][y] == 0 && d[x][y] == -1){//s防止进入墙壁d防止搜索过程回退
d[x][y] = d[p.first][p.second] + 1;
q[++tt] = new Pair(x, y);
}
}
}
System.out.print(d[n][m]);
}
public static void main(String[] args)throws Exception{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String[] params = buf.readLine().split(" ");
n = Integer.valueOf(params[0]);
m = Integer.valueOf(params[1]);
for(int i = 1; i <= n; ++i){//读取数据
String[] info = buf.readLine().split(" ");
for(int j = 1; j <= m; ++j){
s[i][j] = Integer.valueOf(info[j - 1]);
}
}
bfs();
}
}
本文介绍了一种解决迷宫最短路径问题的算法。给定一个由0和1组成的二维数组,0表示可通行的道路,1表示墙壁,算法通过广度优先搜索(BFS)找出从左上角到右下角的最短路径长度。输入包括数组的尺寸和迷宫布局,输出是最少移动次数。
567

被折叠的 条评论
为什么被折叠?



