一道BFS问题,很经典的走迷宫问题,十分生动有趣,也很有实用意义
注意找最快的情况要应用BFS
题目描述
定义一个二维数组:
int maze[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,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
输入
一个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
样例输出
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
分析
找最快的情况要使用BFS,走到相应位置立即停止
#include <bits/stdc++.h>
using namespace std;
bool visited[5][5];
int a[5][5];
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};
//关于x与y的上下左右移动
struct Node{
int x;
int y;
int s;
short l[30];
};
bool panduan(int x,int y)
{//判断此点是否可以走
if(x<0 || x>=5 || y<0 || y>=5)
return true;
if(visited[x][y])
return true;
if(a[x][y]==1)
return true;
return false;
}
Node BFS()
{
queue <Node> q;
Node now,next;
now.x = 0;
now.y = 0;
now.s = 0;
visited[now.x][now.y] = true;
q.push(now);
while(!q.empty()){
now = q.front();
q.pop();
if(now.x==4 && now.y==4)
return now;
int i,nx,ny;
for(i=0;i<4;i++){
nx = now.x + dx[i];
ny = now.y + dy[i];
if(panduan(nx,ny))
continue;
//可以走
next = now;
next.x = nx;
next.y = ny;
next.s = now.s + 1;
next.l[now.s] = i;
q.push(next);
}
}
return now;
}
int main()
{
int i,j;
for(i=0;i<5;i++){ //读入迷宫
for(j=0;j<5;j++){
scanf("%d",&a[i][j]);
}
}
memset(visited,0,sizeof(visited));
Node ans = BFS();
int x,y;
x = 0,y = 0;
for(i=0;i<=ans.s;i++){
printf("(%d, %d)\n",x,y);
x+=dx[ans.l[i]];
y+=dy[ans.l[i]];
}
return 0;
}










