- #include <stdio.h>
- #include <algorithm>
- #include <string.h>
- #include <queue>
- #include <stack>
- using namespace std;
- int dir[]={-1,0,1,0}; ///上下左右四个移动方向
- int dil[]={0,-1,0,1};
- int num[6][6];
- int visit[6][6]; ///表明当前位置是否访问
- int d[30];
- struct node
- {
- int x,y,id;
- }a[30];
- int cet;
- void bfs()
- {
- queue<node>q;
- cet = 0;
- a[cet].x = 0;
- a[cet].y = 0;
- a[cet].id = 0;
- d[0]=-1;
- q.push(a[cet]);
- bool flag = true;
- while(!q.empty()&&flag) ///队列非空且未找到出口
- {
- node xx = q.front();
- int t = xx.id;
- q.pop();
- visit[xx.x][xx.y] = true;
- for(int k=0;k<=3;k++)
- {
- int p = xx.x+dir[k];
- int v = xx.y+dil[k];
- if(!visit[p][v]&&num[p][v]!=1&&p>=0&&p<5&&v>=0&&v<5)
- {
- cet++;
- d[cet] = t;
- a[cet].x = p;
- a[cet].y = v;
- a[cet].id = cet;
- q.push(a[cet]);
- if(a[cet].x==4&&a[cet].y==4) ///找到出口,强制中断,退出搜索
- {
- flag = false;
- break;
- }
- }
- }
- }
- }
- int main()
- {
- for(int i=0;i<5;i++)
- {
- for(int j=0;j<5;j++)
- {
- scanf("%d",&num[i][j]);
- visit[i][j] = false;
- }
- }
- memset(d,-1,sizeof(d));
- bfs();
- stack<node>st;
- while(cet>=0) ///搜索出路径之后,根据之前搜索的信息,将路径反压入栈中,从而进行输出
- {
- st.push(a[cet]);
- cet=d[cet];
- }
- while(!st.empty())
- {
- node ll = st.top();
- printf("(%d, %d)\n",ll.x,ll.y);
- st.pop();
- }
- return 0;
- }
poj 3984 迷宫问题 BFS+栈的使用
猜你喜欢
转载自blog.csdn.net/liuwq012/article/details/50012019
今日推荐
周排行