迷宫问题 POJ - 3984
来源:互联网 发布:淘宝精品服饰广告案例 编辑:程序博客网 时间:2024/06/16 18:30
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 00 1 0 1 00 0 0 0 00 1 1 1 00 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,但是题目上又强调了有唯一解,这说明根据节点的前驱去把整条路径拖出来会很简单。所以还是要用bfs来写。
Code:
#include <iostream>#include <queue>#include <cstdio>using namespace std;typedef struct MAZ { int px; int py;}Maz;Maz a[5][5]; //存下每个点的前驱queue<Maz> que;int maz[5][5];void print(){ int x=4, y=4; Maz ans[26]; int i=0; //cout << a[x][y].px <<',' << a[x][y].py << endl; while ( x != a[x][y].px || y!=a[x][y].py ) { ans[i].px = a[x][y].px; ans[i].py = a[x][y].py; x = ans[i].px; y = ans[i].py; i++; } while (i--) { printf("(%d, %d)",ans[i].px,ans[i].py); if (i) cout << endl; } cout << endl; printf("(4, 4)\n");}bool judege(int x, int y){ if( maz[x][y] ==0 && x >= 0 && x < 5 && y >=0 && y <5 ) return true; else return false;}void push(int x, int y, int px ,int py){ Maz t; t.px = x; t.py = y; que.push(t); a[x][y].px = px; a[x][y].py = py; maz[x][y] += maz[px][py]+1;// printf("(%d,%d)\n",x,y ); //显示拓展顺序}int main() { for (int i = 0; i < 5 ; i++) for(int j = 0 ;j < 5; j++){ cin >> maz[i][j]; if( maz[i][j] == 1 ) maz[i][j] = -1; } maz[0][0] = 1; Maz temp; push(0,0,0,0); while ( !que.empty() ) { temp = que.front(); que.pop(); if (judege(temp.px+1, temp.py)){ push(temp.px+1, temp.py, temp.px, temp.py); } if (judege(temp.px-1, temp.py)){ push(temp.px-1, temp.py, temp.px, temp.py); } if (judege(temp.px, temp.py+1)){ push(temp.px, temp.py+1, temp.px, temp.py); } if (judege(temp.px, temp.py-1)){ push(temp.px, temp.py-1, temp.px, temp.py); } } print();}
0 0
- poj 3984 迷宫问题
- poj 3984 迷宫问题
- POJ-3984-迷宫问题
- Poj 3984 迷宫问题
- 迷宫问题 poj 3984
- poj 3984迷宫问题
- poj 3984 迷宫问题
- POJ-3984-迷宫问题
- poj 3984- 迷宫问题
- POJ 3984 迷宫问题
- poj 3984 迷宫问题
- poj 3984:迷宫问题
- POJ-3984-迷宫问题
- POJ 3984 迷宫问题
- poj 3984迷宫问题
- POJ 3984 迷宫问题
- POJ 3984 迷宫问题
- poj 3984 迷宫问题
- Python常用的几种包(库、模块)安装方式
- stanford-segmenter中文分词基本使用
- jdbc释放连接
- Shell脚本的基本知识
- JavaScript Dom编程艺术 阅读笔记
- 迷宫问题 POJ - 3984
- 动态规划 DP
- html中隐藏域hidden的作用
- 学习笔记---main函数参数-动态存储管理与动态数组
- 汇编语言(王爽) 一
- js学习笔记
- 【t030】数字构造
- 【Python】URL深度采集+源码分析
- Git使用操作