bfs—迷宫问题—poj3984
2024-09-07 11:55:44
迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 20591 | Accepted: 12050 |
http://poj.org/problem?id=3984
Description
定义一个二维数组:
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) bfs过程中记录每个点的上一个点坐标,最后从终点找回到起点,利用栈逆序输出。
#include<iostream>
#include<cstring>
#include<string>
#include<queue>
#include<stack>
#include<set>
using namespace std; const int MAX=;
struct Node
{
int x,y,pace;
bool c;
int prex,prey;//记录上一个点的坐标
}maze[MAX][MAX],t;
int dre[][]={{,},{-,},{,},{,-}};//方向 int main()
{
for(int i=;i<;i++)
for(int j=;j<;j++)
{
cin>>maze[i][j].c;
maze[i][j].x=i;
maze[i][j].y=j;
}
queue<Node> Q;
stack<Node> St;
int X,Y;
Q.push(maze[][]);
while(!Q.empty())
{
t=Q.front();
if(t.x==&&t.y==)//到达右下角
{
St.push(t);
while(t.x!=||t.y!=)//根据上一个点坐标把一条路所有点压入栈
{
t=maze[t.prex][t.prey];
St.push(t);
}
while(!St.empty())//把点逆序输出
{
cout<<"("<<St.top().x<<", "<<St.top().y<<")\n";
St.pop();
}
}
Q.pop();
for(int i=;i<;i++)
{
X=t.x+dre[i][];
Y=t.y+dre[i][];
if(X>=&&X<&&Y>=&&Y<&&maze[X][Y].c==&&!maze[X][Y].pace)
{
maze[X][Y].pace=t.pace+;
maze[X][Y].prex=t.x;//记录上一个点坐标
maze[X][Y].prey=t.y;
Q.push(maze[X][Y]);
}
}
}
return ;
}
最新文章
- css新特性 box-flex/flex 弹性盒状模型
- delphi真随机数发生器
- apache开启虚拟主机localhost无法访问
- Clustering by fast search and find of density peaks
- 琐碎-将hadoop源码作为工程导入eclipse
- VMware: windows8 与 虚拟机ubuntu 14.04 共享文件夹
- struts2对action中的方法进行输入校验---xml配置方式(3)
- CentOS 安装apache 及所需的 apr,apr-util,pcre
- sql中 in 、not in 、exists、not exists 使用方法和区别
- jQuery系列 第一章 jQuery框架简单介绍
- Theorems for existence and uniqueness of variational problem
- ubuntu下core file文件生成及调试
- RefreshListView中onItemClick点击错位
- ABBYY FineReader 12没你想得那么简单
- java基础78 Servlet的生命周期
- hdoj 5119 Happy Matt Friends 背包DP
- 盘点Linux内核源码中使用宏定义的若干技巧(1)
- SpringBoot配置成Liunx服务
- ACE消息队列(转)
- SRAtoolkit软件的使用介绍