题目描述
给定一个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
bfs一般与最短路径问题相关
本题的大概思路如下图
从(0, 0)位置开始,按照距离为1,2,3…进行宽度搜索
java
import java.util.*;
public class Main{
static int N = 110;
static int n, m;
static int[][] g = new int[N][N];
static int[][] d = new int[N][N];
static Queue<Coord> queue = new LinkedList<>(); // 此处也可以安装老师的方法,用数组模拟
private static int bfs() {
queue.offer(new Coord(0, 0));
d[0][0] = 0;
// 四邻域
int[] dx = new int[]{-1, 0, 1, 0};
int[] dy = new int[]{0, 1, 0, -1};
while (!queue.isEmpty()) {
Coord coord = queue.poll();
for (int i = 0; i < 4; i++) {
int x = coord.x + dx[i];
int y = coord.y + dy[i];
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1) {
d[x][y] = d[coord.x][coord.y] + 1;
queue.offer(new Coord(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();
d[i][j] = -1;
}
}
System.out.println(bfs());
}
private static class Coord{
int x;
int y;
Coord(int x, int y) {
this.x = x;
this.y = y;
}
}
}
python
N = 110
g = [[0] * N for i in range(N)]
d = [[-1] * N for i in range(N)]
n, m = 0, 0
def bfs():
global q, n, m
queue = [(0, 0)]
d[0][0] = 0
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
while queue:
px, py = queue.pop(0)
for i in range(4):
x, y = px + dx[i], py + dy[i]
if x >= 0 and x < n and y >= 0 and y < m and g[x][y] == 0 and d[x][y] == -1:
queue.append((x, y))
d[x][y] = d[px][py] + 1
return d[n - 1][m - 1]
def main():
global n, m
n, m = map(int, input().split())
for i in range(n):
t = list(map(int, input().split()))
for j in range(m):
g[i][j] = t[j]
print(bfs())
if __name__ == '__main__':
main()
c++
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int n, m;
int g[N][N]; //地图
int d[N][N]; //距离
PII q[N * N]; //队列,保存地图访问的位置
int bfs(){
int hh = 0, tt = 0;
q[0] = {0, 0}; //(x, y)
memset(d, -1, sizeof d); // -1表示没有走过
d[0][0] = 0;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
while(hh <= tt){
auto t = q[hh ++]; //取出队头元素
for(int i = 0; i < 4; i ++){ //四邻域
int x = t.first + dx[i], y = t.second + dy[i];
if(x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1){
d[x][y] = d[t.first][t.second] + 1;
q[++ tt] = {x, y}; //将当前位置加入到队列中
}
}
}
return d[n - 1][m - 1];
}
int main(){
cin >> n >> m;
for(int i = 0; i < n; i ++){
for(int j = 0; j < m; j ++){
cin >> g[i][j];
}
}
cout << bfs() << endl;
return 0;
}