hdu1072(bfs搜索退出的条件有变)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
struct node
{
    int x,y,step,time;
};
int M[10][10],book[10][10],sx,sy,Next[4][2]={{-1,0},{0,1},{1,0},{0,-1}},n,m;
queue<node>Q;
int bfs()
{
   while(!Q.empty()) Q.pop();
   node first;
   first.x=sx,first.y=sy,first.step=0,first.time=6;
   Q.push(first);
   while(!Q.empty())
   {
       node now,next;
       now=Q.front();
       Q.pop();
       //cout<<now.x<<","<<now.y<<endl;
       for(int i=0;i<4;i++)
       {
           int tx=now.x+Next[i][0];
           int ty=now.y+Next[i][1];
           if(tx<0||ty<0||tx>=n||ty>=m||M[tx][ty]==0||book[tx][ty]||now.time==1)
            continue;
           if(M[tx][ty]==1)
           {
               next.x=tx,next.y=ty,next.step=now.step+1,next.time=now.time-1;
               Q.push(next);
           }
           if(M[tx][ty]==3&&now.time>1)
           {
               printf("%d\n",now.step+1);
               return 1;
           }
           if(M[tx][ty]==4)
           {
               book[tx][ty]=1;
               next.x=tx,next.y=ty,next.step=now.step+1,next.time=6;
               Q.push(next);
           }
       }
   }
   return 0;
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d %d",&n,&m);
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                scanf("%d",&M[i][j]);
                if(M[i][j]==2)
                {
                    sx=i,sy=j;
                }
            }
        }
        memset(book,0,sizeof(book));
        if(!bfs())
            printf("-1\n");

    }
}

你可能感兴趣的:(hdu1072(bfs搜索退出的条件有变))