67.迷宫问题(广搜)

67.迷宫问题(广搜)

样例输入1

5 9

1 1 4 9

0 -1 0 0 0 0 0 0 -1

0 0 0 0 -1 0 0 0 -1

-1 0 0 0 0 0 -1 -1 -1

0 0 -1 -1 0 0 0 0 0

0 0 0 0 0 0 0 -1 -1

样例输出1

(1,1)->(2,1)->(2,2)->(2,3)->(2,4)->(3,4)->(3,5)->(3,6)->(4,6)->(4,7)->(4,8)->(4,9)

样例输入2

5

2 1

8 4

-1  -1 -1  -1 -1

  -1

-1  -1 -1  -1

-1  -1

-1  -1 -1

-1  -1

-1  -1 -1  -1

-1  -1

样例输出2

(2,1)->(2,2)->(2,3)->(2,4)->(3,4)->(4,4)->(4,3)->(5,3)->(6,3)->(6,4)->(7,4)->(8,4)

样例输入3

8 5

2 1

8 4

-1  -1 -1 -1 -1

  0 -1

-1  -1 -1  0 -1

-1  0 -1

-1  0 -1 -1

-1  0 -1

-1  -1 -1 -1 -1

-1  0 -1

样例输出3

no way

代码:
一:广搜:

#include

using namespace std;

#include

int n,m,qx,qy,zx,zy;

int jz[101][101];

int pre[101];

int xx[]={0,0,1,-1};

int yy[]={1,-1,0,0};

struct Point{

       int x,y;

};

Point point[101];

void input()

{

       scanf("%d%d",&n,&m);

       scanf("%d%d%d%d",&qx,&qy,&zx,&zy);

       for(int i=1;i<=n;++i)

         for(int j=1;j<=m;++j)

         scanf("%d",&jz[i][j]);

      

}

void out(int d)

{

       if(pre[d])

       out(pre[d]);

       printf("(%d,%d)->",point[d].x,point[d].y);

}

void BFS()

{

       int head=0,tail=1;

       point[tail].x=qx;

       point[tail].y=qy;

       pre[tail]=0;

       while(head

       {

              ++head;

              int x0=point[head].x,y0=point[head].y;

              for(int i=0;i<4;++i)

              {

                     int x1=x0+xx[i],y1=y0+yy[i];

                     if(x1>=1&&x1<=n&&y1>=1&&y1<=m&&jz[x1][y1]==0)

                     {

                            jz[x1][y1]=-1;

                            ++tail;

                            pre[tail]=head;

                            point[tail].x=x1;

                            point[tail].y=y1;

                     }

                     if(point[tail].x==zx&&point[tail].y==zy)

                     {

                            out(pre[tail]);

                            printf("(%d,%d)",point[tail].x,point[tail].y);

                            return ;

                     }

              }

       }

       printf("no way");

       return;

}

int main()

{

       freopen("1.out","w",stdout);

       input();

       BFS();

       return 0;

}

posted on 2016-03-12 18:59  142141241  阅读(141)  评论(0编辑  收藏  举报

导航