题目
走迷宫问题
Description
给定一个 n×m的二维整数数组,用来表示一个迷宫,数组中只包含 0或 1,其中 0表示可以走的路,1表示不可通过的墙壁。
最初,有一个人位于左上角 (1,1)处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。
请问,该人从左上角移动至右下角 (n,m)处,至少需要移动多少次。
数据保证 (1,1) 处和 (n,m)处的数字为 0,且一定至少存在一条通路。
Input
第一行包含两个整数 n和 m。
接下来 n行,每行包含 m个整数(0或 1),表示完整的二维数组迷宫。
1 <= n,m<=100
Output
输出一个整数,表示从左上角移动至右下角的最少移动次数。
思路
一个二维数组Maze[][]记录迷宫,另一个二维数组dist[][]记录对应坐标到入口的最短步骤。
宽搜(BFS)能确保找到的是最短路径(最少的移动步数)。
将开始位置的坐标放进队列,并设置入口位置的dist[][]为零。
开始循环,当队列不为空时,执行循环体。
循环体中将队列的第一个元素弹出,并将它的四个方向的坐标来判断,如果满足条件则添加到队列,并将对应坐标到入口的距离+1。
循环执行,直至队列为空。
出口对应的dist[][]即为所求。
C++实现
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
#define MAX 100
int n, m;
int Maze[MAX][MAX];
int dist[MAX][MAX];
int BFS()
{
queue<pair<int, int>> queue;
queue.push({ 0, 0 });
memset(dist, -1, sizeof(dist));
dist[0][0] = 0;
int dx[4] = { -1, 0, 1, 0 }, dy[4] = { 0, 1, 0, -1 };
while (!queue.empty())
{
auto temp = queue.front();
queue.pop();
for (int i = 0; i < 4; i++)
{
int x = temp.first + dx[i], y = temp.second + dy[i];
if (x >= 0 && x < n && y >= 0 && y < m && Maze[x][y] == 0 && dist[x][y] == -1)
{
dist[x][y] = dist[temp.first][temp.second] + 1;
queue.push({ x, y });
/*cout << "(" << x << "," << y << ")" << endl;
cout << "-------------" << endl;*/
}
}
}
return dist[n - 1][m - 1];
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++) {
cin >> Maze[i][j];
}
}
cout << BFS() << endl;
return 0;
}
java实现
import java.util.LinkedList;
import java.util.Scanner;
public class MazeProblem{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int Maze[][] = new int[n][m]; //迷宫
int dist[][] = new int[n][m]; //记录该该位置到入口的最短距离
//迷宫初始化
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
Maze[i][j] = sc.nextInt();
dist[i][j] = -1;
}
}
int stare[] = new int[]{0,0};//起点坐标
int directions[][] = new int[][]{{-1,0},{0,1},{1,0},{0,-1}};//四个方向
dist[0][0] = 0;//起点
//宽搜(BFS)找到最短路径
LinkedList<int[]> queue = new LinkedList<>();
queue.add(stare);
while(!queue.isEmpty()){
int temp[] = queue.poll();
for (int[] direction : directions) {
int x = temp[0]+direction[0];
int y = temp[1]+direction[1];
if(x>=0 && x<n && y>=0 && y<m && Maze[x][y] == 0 && dist[x][y] == -1){
dist[x][y] = dist[temp[0]][temp[1]]+1;
queue.add(new int[]{x,y});
// System.out.println("("+x+","+y+")");
// System.out.println("-------------");
}
}
}
System.out.println(dist[n-1][m-1]);
sc.close();
}
}
温馨提示:使用java提交算法题时记得将类名改为Main。