题目链接:http://poj.org/problem?id=3984

迷宫问题
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 24560   Accepted: 14338

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输出路径。

由于每个格子只能从一个格子转移过来(开始格子除外),所以开了fa[x][y][2]三维数组来存格子xy的上一个格子。

代码如下:

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <set>
#define ms(a,b) memset((a),(b),sizeof((a)))
using namespace std;
typedef long long LL;
const int INF = 2e9;
const LL LNF = 9e18;
const int MOD = 1e9+;
const int MAXN = +; struct node
{
int x, y;
};
int m[MAXN][MAXN], fa[MAXN][MAXN][], vis[MAXN][MAXN];
int dir[][] = { ,,,,-,,,- }; queue<node>que;
void bfs()
{
while(!que.empty()) que.pop();
node now, tmp;
now.x = now.y = ;
vis[][] = ;
que.push(now); while(!que.empty())
{
now = que.front();
que.pop(); if(now.x== && now.y==)
return;
for(int i = ; i<; i++)
{
tmp.x = now.x + dir[i][];
tmp.y = now.y + dir[i][];
if(tmp.x>= && tmp.x<= && tmp.y>= && tmp.y<= && !vis[tmp.x][tmp.y] && !m[tmp.x][tmp.y])
{
vis[tmp.x][tmp.y] = ;
fa[tmp.x][tmp.y][] = now.x;
fa[tmp.x][tmp.y][] = now.y;
que.push(tmp);
}
}
}
} void Print(int x, int y)
{
if(x!= || y!=)
Print(fa[x][y][], fa[x][y][]);
printf("(%d, %d)\n", x,y);
} int main()
{
for(int i = ; i<; i++)
for(int j = ; j<; j++)
scanf("%d",&m[i][j]); bfs();
Print(,);
}

最新文章

  1. react-native DatePicker日期选择组件的实现
  2. [LeetCode] Remove Duplicates from Sorted List 移除有序链表中的重复项
  3. 解决hibernate删除时的异常
  4. AspxSpy2014 Final
  5. [转载]C# Random 生成不重复随机数
  6. 使用jsonEditor打造一个复杂json编辑器
  7. 一个简单的Java死锁示例(转)
  8. JavaScript中变量声明有var和没var的区别
  9. echarts配合循环计时器等出现的内存泄漏
  10. 性能测试平台效率优化的一次经验(python版)
  11. 一个web应用的诞生(11)--列表分页
  12. Java WebService接口生成和调用 图文详解&gt;【转】【待调整】
  13. Java 获取当前日期的几种方法
  14. Android 弹性布局 FlexboxLayout了解一下
  15. python解决SyntaxError: Non-ASCII character &#39;\xe6&#39;
  16. C调用lua的table里面的函数
  17. ubuntu 连接windows远程桌面 &&rdesktop 退出全屏模式
  18. 分页导航jsp
  19. Netty源码分析第5章(ByteBuf)----&gt;第8节: subPage级别的内存分配
  20. day7回顾

热门文章

  1. win10安装virtualbox发生严重错误
  2. cf468B Two Sets
  3. EC++学习笔记(一) 习惯c++
  4. POJ2167 Irrelevant Elements
  5. AC日记——[USACO1.1]坏掉的项链Broken Necklace 洛谷 P1203
  6. Struts2的标签三大类是什么?
  7. ubuntu下安装翻译软件
  8. luogu P1476 休息中的小呆
  9. Linux下文件操作命令cat(转)
  10. Spring boot 整合spring Data JPA+Spring Security+Thymeleaf框架(上)