博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

poj 3984 迷宫问题

Posted on 2016-01-13 16:33  shaoweiyi  阅读(161)  评论(0编辑  收藏  举报

宽度优先搜索

宽搜解决最短路问题

深搜解决连通块和可行解问题

自己写的队列(path)

  1 #include <iostream>
  2 #include<cstdio>
  3 #include <vector>
  4 #include <sstream>
  5 #include <string>
  6 #include <cstring>
  7 #include <cmath>
  8 #include <stack>
  9 #include <algorithm>
 10 using namespace std;
 11 
 12 const int MAXL=10;
 13 char maze [MAXL][MAXL];
 14 bool visit[MAXL][MAXL];///初始化为false.
 15 int n=5;
 16 int m=5;
 17 int dirx[4]={0,0,1,-1};
 18 int diry[4]={1,-1,0,0};
 19 typedef struct
 20 {
 21     int x;
 22     int y;
 23 }P;
 24 P path[MAXL*MAXL];
 25 int pre[MAXL*MAXL];
 26 P start,finil;
 27 ///path pre visit
 28 
 29 
 30 
 31 /*void output( )
 32 {
 33 for(int i=0;i<n;++i)
 34  {
 35  for(int j=0;j<m;++j)
 36   {
 37    cout<<(int)maze[i][j]<<" ";
 38   }
 39   cout<<endl;
 40  }
 41 }*/
 42 void output(int i)
 43 {
 44 if(pre[i]==-1) printf("(%d, %d)\n",path[i].x,path[i].y);
 45 else
 46 {
 47 output(pre[i]);
 48 printf("(%d, %d)\n",path[i].x,path[i].y);
 49 }
 50 }
 51 
 52 void input()
 53 {
 54 for(int i=0;i<n;++i)///行号
 55 {
 56   for(int j=0;j<m;++j)
 57     {
 58        scanf("%c",&maze[i][j]);
 59        maze[i][j]-='0';
 60        if(j<m-1) getchar();
 61     }
 62      getchar();
 63  }
 64  start.x=0;
 65  start.y=0;
 66  finil.x=4;
 67  finil.y=4;
 68 /// output();
 69 }
 70 
 71 void bfs()
 72 {
 73     int head,tail;
 74     tail=head=0;///tail前的为尾位置
 75     P current,next;
 76     tail=1;
 77     path[0]=start;
 78     pre[0]=-1;
 79     visit[start.x][start.y]=1;
 80   while(head<tail)
 81   {
 82       current=path[head];
 83       if(current.x==finil.x&&current.y==finil.y)
 84         {
 85             output(head);
 86             break;
 87        }
 88       for(int i=0;i<4;++i)
 89       {
 90 
 91        next.x=current.x+dirx[i];
 92        next.y=current.y+diry[i];
 93        if(!visit[next.x][next.y]&&!maze[next.x][next.y]&&next.x>=0&&next.x<m&&next.y>=0&&next.y<n)
 94        {
 95            visit[next.x][next.y]=1;
 96            path[tail]=next;
 97            pre[tail]=head;
 98            tail++;
 99        }
100       }
101       head++;///chudui
102   }
103   return;
104 }
105 
106 
107 
108 int main()
109 {
110 input();
111 
112 bfs();
113 return 0;
114 }