poj 3984 迷宫问题 BFS+栈的使用

  1. #include <stdio.h>  
  2. #include <algorithm>  
  3. #include <string.h>  
  4. #include <queue>  
  5. #include <stack>  
  6. using namespace std;  
  7. int dir[]={-1,0,1,0};  ///上下左右四个移动方向
  8. int dil[]={0,-1,0,1};  
  9. int num[6][6];  
  10. int visit[6][6];  ///表明当前位置是否访问
  11. int d[30];  
  12. struct node  
  13. {  
  14.     int x,y,id;  
  15. }a[30];  
  16. int cet;  

  17. void bfs()  
  18. {  
  19.     queue<node>q;  
  20.     cet = 0;  
  21.     a[cet].x = 0;  
  22.     a[cet].y = 0;  
  23.     a[cet].id = 0;  
  24.     d[0]=-1;  
  25.     q.push(a[cet]);  
  26.     bool flag = true;  
  27.     while(!q.empty()&&flag)  ///队列非空且未找到出口
  28.     {  
  29.         node xx = q.front();  
  30.         int t = xx.id;  
  31.         q.pop();  
  32.         visit[xx.x][xx.y] = true;  
  33.         for(int k=0;k<=3;k++)  
  34.         {  
  35.             int p = xx.x+dir[k];  
  36.             int v = xx.y+dil[k];  
  37.             if(!visit[p][v]&&num[p][v]!=1&&p>=0&&p<5&&v>=0&&v<5)  
  38.             {  
  39.                 cet++;  
  40.                 d[cet] = t;  
  41.                 a[cet].x = p;  
  42.                 a[cet].y = v;  
  43.                 a[cet].id = cet;  
  44.                 q.push(a[cet]);  
  45.                 if(a[cet].x==4&&a[cet].y==4)  ///找到出口,强制中断,退出搜索
  46.                 {  
  47.                     flag = false;  
  48.                     break;  
  49.                 }  
  50.             }  
  51.         }  
  52.     }  
  53. }  
  54. int main()  
  55. {  
  56.     for(int i=0;i<5;i++)  
  57.     {  
  58.         for(int j=0;j<5;j++)  
  59.         {  
  60.             scanf("%d",&num[i][j]);  
  61.             visit[i][j] = false;  
  62.         }  
  63.     }  
  64.     memset(d,-1,sizeof(d));  
  65.     bfs();  
  66.     stack<node>st;  
  67.     while(cet>=0)  ///搜索出路径之后,根据之前搜索的信息,将路径反压入栈中,从而进行输出
  68.     {  
  69.         st.push(a[cet]);  
  70.         cet=d[cet];  
  71.     }  
  72.     while(!st.empty())  
  73.     {  
  74.         node ll = st.top();  
  75.         printf("(%d, %d)\n",ll.x,ll.y);  
  76.         st.pop();  
  77.     }  
  78.     return 0;  
  79. }  

猜你喜欢

转载自blog.csdn.net/liuwq012/article/details/50012019