基础迷宫问题-------------(图的BFS 题目取自算法竞赛入门)
2013-09-20 20:11
886 查看
解题思想为用BFS,按距离为参考将每个节点连成树状结构,再从终点反向查找起点,将路径放入stack,最后输出起点到终点的路径。
#include <iostream> #include <fstream> #include <cstring> #include <queue> #include <stack> using namespace std; #define maxn 100 //0 set as blank, 1 set as wall typedef struct{ int i; int j; }pos; typedef struct{ char pointer; int i; int j; }mov; mov mov_flag[4]={{'r', 0, 1}, {'d', 1, 0}, {'l', 0, -1}, {'u', -1, 0} }; //reverse name see from father node class maze{ public: maze(const int &m, const int &n):row(m), column(n){ for(int i = 0; i <= row + 1; i++) for(int j = 0; j <= column + 1; j++) map[i][j] = 1; } int print_way(const int &m , const int &n, const int &out_m, const int &out_n); private: friend ifstream & operator>>(ifstream &in, class maze &out); friend ostream & operator<<(ostream &out, class maze &in); const int row; const int column; int map[maxn][maxn]; }; ifstream & operator>>(ifstream & in, class maze &out){ for(int i = 1; i <= out.row; i++) for(int j = 1; j <= out.column; j++){ in>>out.map[i][j]; } return in; } ostream & operator<<(ostream &out, class maze &in) { for(int i = 0; i <= in.row + 1; i++){ for(int j = 0; j <= in.column + 1; j++){ out << in.map[i][j] << " "; } cout << endl; } return out; } int maze::print_way(const int &m, const int &n, const int &out_m, const int &out_n) { int dir[maxn][maxn]; int vis[maxn][maxn]; memset(vis, 0, sizeof(vis)); memset(dir, 0, sizeof(dir)); pos tmp; if(map[m] == 1) return -1; queue<pos>store; tmp.i = m; tmp.j = n; store.push(tmp); while(!store.empty()){ tmp = store.front(); store.pop(); int x, y; for(int flag = 0; flag < 4; flag++){ vis[tmp.i][tmp.j] = 1; x = tmp.i + mov_flag[flag].i; y = tmp.j + mov_flag[flag].j; if(0 == vis[x][y] && 0 == map[x][y]){ dir[x][y] = flag; //set mov dir point to father pos new_add; new_add.i = x; new_add.j = y; store.push(new_add); //push node into queue } } } int i = out_m; int j = out_n; stack<char>way; while(i != m || j != n){ int x, y, flag; flag = dir[i][j]; way.push(mov_flag[flag].pointer); x = mov_flag[flag].i; y = mov_flag[flag].j; i -= x; j -= y; } while(!way.empty()){ cout << " mov " << way.top() << "\n"; way.pop(); } return 0; } int main() { maze test(10,10); ifstream map("map", fstream::in); map >> test; cout << test; test.print_way(1, 1, 10, 10); return 0; }
相关文章推荐
- 算法竞赛入门经典:第五章 基础题目选解 5.3 周期串
- 走迷宫问题 算法竞赛入门经典
- 算法竞赛入门经典:第六章 数据结构基础 6.11迷宫
- 算法竞赛入门经典:第五章 基础题目选解 5.11果园里的树
- 【索引】算法竞赛入门经典-第5章 基础题目选解
- 算法竞赛入门经典:第六章 数据结构基础 6.12迷宫路径
- 算法竞赛入门经典:第五章 基础题目选解 5.9 Cantor数
- 算法竞赛入门经典 8.3.2循环日程表问题
- bfs入门 poj 3984 迷宫问题
- 最简单的BFS入门题目——迷宫的最短路径
- 0-1背包 (算法竞赛入门经典0-1背包问题)
- 基础BFS 邻接矩阵Flood fill 算法题目总结
- 算法竞赛入门——6174问题
- 算法竞赛入门-八皇后问题
- 刘汝佳p41,3-4(竖式问题)算法竞赛入门经典第二版
- 算法竞赛入门经典-第五章6174问题
- 算法竞赛入门:埃及分数问题
- Uva 101 the block problem 木块问题(算法竞赛经典入门)STL vector
- 迷宫问题_BFS_挑战程序设计竞赛p34
- 【算法竞赛入门经典】6.5[图的BFS] 例题6-20 UVa1599 (2)