回溯算法之迷宫问题
2012-10-24 19:30
316 查看
题意:
迷宫问题,大家都懂的
迷宫问题,大家都懂的
#include<iostream> #include<stdio.h> #include<stack> #include<string.h> using namespace std; #define max 1000 int map[max][max]; int visit[max][max]; int row,col; int sx,sy,ex,ey; typedef struct node { int x; int y; int step; int dir; } position; stack<struct node> stack2; int dir[4][2]={0,1,1,0,0,-1,-1,0}; int mazePath() { position cur; cur.x=sx; cur.y=sy; cur.step=0; cur.dir=0; do { if((cur.x>=0&&cur.x<row)&&(cur.y>=0&&cur.y<col)&&visit[cur.x][cur.y]==1) { stack2.push(cur); visit[cur.x][cur.y]=0; if(cur.x==ex&&cur.y==ey) return 1; cur.x=cur.x+dir[0][0]; cur.y=cur.y+dir[0][1]; cur.step++; cur.dir=0; } else { position testpos=stack2.top(); stack2.pop(); while(testpos.dir==3) { testpos=stack2.top(); stack2.pop(); visit[testpos.x][testpos.y]=1; } if(testpos.dir<3) { testpos.dir++; stack2.push(testpos); cur.x=testpos.x+dir[testpos.dir][0]; cur.y=testpos.y+dir[testpos.dir][1]; } } }while(!stack2.empty()); return 0; } void printPath() { stack<position> stack1; while(!stack2.empty()) { stack1.push(stack2.top()); stack2.pop(); } while(!stack1.empty()) { position q=stack1.top(); stack1.pop(); printf("%d %d\n",q.x,q.y); } } int main() { scanf("%d%d",&row,&col); for(int i=0;i<max;i++) { for(int j=0;j<max;j++) visit[i][j]=1; } for(int i=0;i<row;i++) { for(int j=0;j<col;j++) scanf("%d",&visit[i][j]); } scanf("%d%d%d%d",&sx,&sy,&ex,&ey); if(mazePath()) printPath(); else printf("no path\n"); return 0; }
相关文章推荐
- 回溯算法经典应用之—迷宫问题 (Java)
- C语言链栈以及回溯算法解决迷宫问题
- 回溯算法基础---皇后问题,骑士游历,迷宫求解
- 迷宫问题回溯算法
- 数据结构与算法学习之路:迷宫问题——回溯思想找出所有路径
- C++搜索与回溯算法之素数环问题
- 0-1背包问题-回溯&贪心算法-C#Demo
- 算法提高 学霸的迷宫 经典广搜bfs问题
- 回溯法解决迷宫搜索问题
- 回溯法解八皇后、幕集输出、迷宫问题
- Java利用回溯思想解决迷宫问题(寻找最短路径)
- 回溯算法—n皇后问题
- LV算法和回溯法结合解n后问题
- 算法学习:回溯解决4皇后问题
- 回溯算法之N皇后问题
- C++ 迷宫问题的回溯解法
- 迷宫问题的算法(优于递归、深度优先、广度优先)
- JAVA代码—算法基础:0-1背包问题的回溯算法设计(续)
- GDI+学习(7) 八皇后问题回溯算法演示系统
- 回溯算法---八皇后问题