迷宫问题
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 ;
}

最新文章

  1. css新特性 box-flex/flex 弹性盒状模型
  2. delphi真随机数发生器
  3. apache开启虚拟主机localhost无法访问
  4. Clustering by fast search and find of density peaks
  5. 琐碎-将hadoop源码作为工程导入eclipse
  6. VMware: windows8 与 虚拟机ubuntu 14.04 共享文件夹
  7. struts2对action中的方法进行输入校验---xml配置方式(3)
  8. CentOS 安装apache 及所需的 apr,apr-util,pcre
  9. sql中 in 、not in 、exists、not exists 使用方法和区别
  10. jQuery系列 第一章 jQuery框架简单介绍
  11. Theorems for existence and uniqueness of variational problem
  12. ubuntu下core file文件生成及调试
  13. RefreshListView中onItemClick点击错位
  14. ABBYY FineReader 12没你想得那么简单
  15. java基础78 Servlet的生命周期
  16. hdoj 5119 Happy Matt Friends 背包DP
  17. 盘点Linux内核源码中使用宏定义的若干技巧(1)
  18. SpringBoot配置成Liunx服务
  19. ACE消息队列(转)
  20. SRAtoolkit软件的使用介绍

热门文章

  1. iSCSI集群与存储
  2. Mysql主从搭建(1)
  3. (二) vim的Tabbar插件
  4. javascript入门 之 zTree(十四 增删查改)(二)
  5. mysql yum源安装
  6. canal使用记录
  7. std::string::substr函数
  8. 数据结构和算法(Golang实现)(13)常见数据结构-可变长数组
  9. ASE past project:interview &amp; analysis
  10. A - Chat Group Gym-101775A