HDU 1072 Nightmare

鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1072

題意比較好理解,這裏就不多做解釋了,像我英語這麼差的人都讀的懂,別人更應該就沒什麼了尷尬。看到題目肯定想到是BFS好寫,是一道限時的題目,但是當你到有Bomb-Rest-Equipment的地方時,時間又會恢復到6秒,所以走的步數最少不一定用的時間就最少,題目是要求出最短時間,所以我在寫結構體時即定義了時間,又定義了步數。寫的時候還是出現了很多問題,唉,Wa了好多次,後來參考了網上的代碼,看到了他們開了一個數組,代表走到這一點還剩餘的最大時間,用if(next.time>1&&T[next.x][next.y]<next.time)進行判斷,然後過了。都是淚啊。不過個人感覺這個題目還是挺值的做的。。很適合初學者。

代碼:

#include <cstring>
#include <cstdio>
#include <queue>

using namespace std;
 int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
 int map[9][9];
 int T[9][9];
 int si,sj;
 int n,m;
 struct point
 {
     int x,y,time,step;
 }start;

 int BFS(int a,int b)
 {
     queue<point> q;
     point cur,next;
     int i;

     start.x=a;
     start.y=b;
     start.step=0;
     start.time=6;

     q.push(start);

     while(!q.empty())
     {

         cur=q.front();
         q.pop();

         for(i=0;i<4;i++)
         {
            next.x=cur.x+dir[i][0];
            next.y=cur.y+dir[i][1];
            next.time=cur.time-1;
            next.step=cur.step+1;

             if(map[next.x][next.y]==3)
                return next.step;

            if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m)
            {
                if(map[next.x][next.y]!=0)
                {
                    if(map[next.x][next.y]==4&&next.time>0)
                        next.time=6;
                    if(next.time>1&&T[next.x][next.y]<next.time) 
                    {
                        // If Ignatius get to the exit when the exploding time turns to 0, he can't get out of the labyrinth

                       //map[next.x][next.y]=0;    題目規定走過的還可以走的。
                       T[next.x][next.y]=next.time;
                       q.push(next);
                    }
                }
            }

         }
     }
     return -1;
 }

int  main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);

    int i,j,t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);

        for(i=0;i<n;i++)
        {

            for(j=0;j<m;j++)
            {

                scanf("%d",&map[i][j]);
                if(map[i][j]==2)
                {

                    si=i;
                    sj=j;
                }
            }

        }

        memset(T,0,sizeof(T));
        T[si][sj]=6;
        map[si][sj]=0;

        int count=BFS(si,sj);

       printf("%d\n",count);
    }
    return 0;
}


 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章