走出迷宫
2013-12-30 10:49
281 查看
用矩阵建立图,s为迷宫的起点,t为迷宫的终点,输出走出迷宫路线的坐标
步骤:
1)建立栈
2)判断下一步是否可达,可达则结束判断
3)不可达则前进,按上下左右地前进。
步骤:
1)建立栈
2)判断下一步是否可达,可达则结束判断
3)不可达则前进,按上下左右地前进。
/* 迷宫求解 6 #s#### #O#### #O#### #O#### #OOOOt ###### 10 ########## #sO#OOO#O# #OO#OOO#O# #OOOO##OO# #O###OOOO# #OOO#OOOO# #O#OOO#OO# #O###O##O# ##OOOOOOt# ########## */
#include <iostream> #include <stack> using namespace std; #define MAX 1000 struct Node { int x, y; }tmp, s, t, order[MAX]; char Graph[MAX][MAX]; int IsFind(int x, int y) { if (x==t.x && y==t.y) return 1; return 0; } int Judge(stack<struct Node> &sta) //判断是否到达t { if (IsFind(tmp.x+1, tmp.y)) { tmp.x = tmp.x + 1; sta.push(tmp); return 1; } else if (IsFind(tmp.x-1, tmp.y)) { tmp.x = tmp.x - 1; sta.push(tmp); return 1; } else if (IsFind(tmp.x, tmp.y+1)) { tmp.y = tmp.y + 1; sta.push(tmp); return 1; } else if (IsFind(tmp.x, tmp.y-1)) { tmp.y = tmp.y - 1; sta.push(tmp); return 1; } return 0; } void Advance(stack<struct Node> &sta) { if (Graph[tmp.x+1][tmp.y]=='O') { Graph[tmp.x][tmp.y] = '#'; tmp.x = tmp.x + 1; sta.push(tmp); } else if (Graph[tmp.x-1][tmp.y]=='O') { Graph[tmp.x][tmp.y] = '#'; tmp.x = tmp.x - 1; sta.push(tmp); } else if (Graph[tmp.x][tmp.y+1]=='O') { Graph[tmp.x][tmp.y] = '#'; tmp.y = tmp.y + 1; sta.push(tmp); } else if (Graph[tmp.x][tmp.y-1]=='O') { Graph[tmp.x][tmp.y] = '#'; tmp.y = tmp.y - 1; sta.push(tmp); } else { tmp = sta.top(); Graph[tmp.x][tmp.y] = '#'; sta.pop(); } } int main() { int num, i, j; while (cin>>num && num) { for (i=0; i<num; i++) for (j=0; j<num; j++) { cin>>Graph[i][j]; if (Graph[i][j]=='s') { s.x = i, s.y = j;} else if (Graph[i][j]=='t') {t.x = i, t.y = j;} } stack<struct Node> sta; sta.push(s); while (!sta.empty()) { tmp = sta.top(); if (Judge(sta))//下一步是否可达 break; Advance(sta);//前进 } if (sta.empty()) cout<<"找不到出口"<<endl; else { j = i = sta.size(); while (!sta.empty()) { order[i] = sta.top(); sta.pop(); i--; } for (i=1; i<=j; i++) { if (i==1) cout<<'('<<order[i].x<<','<<order[i].y<<')'; else cout<<"->("<<order[i].x<<','<<order[i].y<<')'; } cout<<endl; } } return 0; }
相关文章推荐
- 走出 JNDI 迷宫
- 这几件事带你走出深陷的数据分析迷宫
- 走出MFC窗口子类化的迷宫
- 走出MFC子类化的迷宫:子类化,SUBCLASSWINDOW,MFC消息机制
- 走出Java资源加载的迷宫
- 走出MFC子类化的迷宫:子类化,SUBCLASSWINDOW ,MFC消息机制 ---(摘自CSDN论坛)
- (转)走出MFC子类化的迷宫:子类化,SUBCLASSWINDOW ,MFC消息机制
- 走出Java资源加载的迷宫
- 翻译:走出类加载器迷宫
- 走出J2ME游戏开发迷宫--J2ME游戏开发框架及实施
- 自动寻找走出迷宫的最短路径
- 翻译:走出类加载器迷宫
- 走出MFC窗口子类化的迷宫
- 走出MFC子类化的迷宫
- (转)走出MFC子类化的迷宫:子类化,SUBCLASSWINDOW ,MFC消息机制 ---(摘自CSDN论坛)
- 走出Java资源加载的迷宫
- 走出迷宫功能【误】
- 走出MFC窗口子类化的迷宫
- (转)走出MFC子类化的迷宫:子类化,SUBCLASSWINDOW ,MFC消息机制 ---(摘自CSDN论坛)
- 走出这个迷宫