简单搜索 迷宫问题
问题描述
定义一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
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
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
这是写OJ第一次完全靠自己写,并且提交成功的题目,虽然题目不难,不过有个点也卡了我很久。
思路
这是一个典型的BFS问题,唯一的难点就是输出的时候要将所有的步骤打印出来。总体思路就是从初始点(0,0)开始,每次都有四个方向可以移动。不过不可以超过边界、不可以去有墙的位置以及不去以及去过的位置。定义一个结构体,除了x,y坐标,步数之外还需要定义一个数组来保存步骤。当结构体的(x,y)=(4,4)的时候,就返回结构体。然后输入保存了步骤的那个数组即可。代码如下
代码
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
int map[6][6];
int dir[4][2]={{0,-1},{0,1},{-1,0},{1,0}};
int visited[6][6];
struct point
{
int x,y,z;
int step;
int move[25][2];
};
point bfs()
{ int startx=0;int starty=0;int endx=4;int endy=4;
point news,now;
queue<point> t;
now.x=startx;now.y=starty;now.step=0;
visited[now.x][now.y]=1;
t.push(now);
while(!t.empty())
{
now=t.front();
t.pop();
if(now.x==endx&&now.y==endy) return now;
for(int i=0;i<4;i++)
{
news=now; //注意这里每次循环都要重新将now赋给news
news.x=news.x+dir[i][0];
news.y=news.y+dir[i][1];
if(news.x>=5||news.x<0||news.y<0||news.y>=5 ||map[news.x][news.y]==1 || visited[news.x][news.y]==1)
{
visited[news.x][news.y]=1;
continue;
}
visited[news.x][news.y]=1;
news.move[news.step][0]=news.x;
news.move[news.step][1]=news.y;
news.step=now.step+1;
t.push(news);
}
}
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
{
cin>>map[i][j] &&map[i][j]<=1&&map[i][j]>=0;
}
point ans=bfs();
cout<<"(0, 0)"<<endl;
for(int i=0;i<ans.step;i++)
{
cout<<"("<<ans.move[i][0]<<", "<<ans.move[i][1]<<")"<<endl;
}
return 0;
}
本文详细解析了一个使用BFS算法解决迷宫最短路径问题的实例。通过定义一个二维数组表示迷宫,其中1表示墙壁,0表示通路,文章展示了如何寻找从左上角到右下角的最短路径。代码实现中,运用了结构体存储坐标、步数及路径,配合队列进行广度优先搜索,最终输出路径。
554

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



