HDU1072

来源:互联网 发布:java 读取usb接口数据 编辑:程序博客网 时间:2024/05/16 19:55

又WA了好多遍,没意思到如果先建立QUE的时候,而在BFS中没有清空,QUE有可能会存留上次数据



#include <iostream>

#include <stdio.h>
#include <string.h>
#include <queue>
#define maxn 50
//queue<point> que;

using namespace std;


struct point
{
    int x,y;
    int time;
    int step;
}now,temp;


char map[maxn][maxn];
int minute[maxn][maxn];
int move[4][2] = {{1,0}, {-1, 0}, {0,1}, {0,-1}};


int sx,sy,endx, endy;
int n,m;






int bfs()
{
   bool flag = false;

//while(!que.empty())

  // que.pop();


   temp.x = sx;
   temp.y = sy;
   temp.time = 0;
   temp.step = 0;
queue<point>que;


   que.push(temp);




    while(!que.empty())
    {
        temp = que.front();
        que.pop();


        for( int i = 0; i<4; i++)
        {
            now = temp;


            now.x += move[i][0];
            now.y +=  move[i][1];


            now.time++;
            now.step++;


           if(map[now.x][now.y] == '0'|| now.time >= 6)
                continue;


         else if(map[now.x][now.y] == '3')
              return now.step;// 如果不是在调用时建立que,也没有代码清空que时,会对下次数据造成影响
         else if( map[now.x][now.y] == '1' && now.time < minute[now.x][now.y] )
               {
                   minute[now.x][now.y] = now.time;//可重复走所以要保存的是经过此点的最小时间,
                   que.push(now);
               
               }


        else if( map[now.x][now.y] == '4' )
             {
                 map[now.x][now.y]='0';
                 now.time = 0;
                 que.push(now);
             }


        }
    }


   return -1;


}


int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        memset(map,'0',sizeof(map));
        memset(minute,maxn,sizeof(minute));


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




        for( int i =1; i<=n; i++)
        {
            getchar();
            for( int j =1; j<=m; j++)
             {
                 cin>>map[i][j];
                 if(map[i][j] == '2')
                 {
                     sx = i;
                     sy = j;
                 }
             }
        }
        cout<<bfs()<<endl;;
    }
    return 0;
}



0 0
原创粉丝点击