HDU 1072 [Nightmare] BFS

來源:互聯網
上載者:User

標籤:思想   代碼   algo   struct   pre   不能   map   --   ble   

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1072

題目大意:給一個地圖,從起點開始往終點走,6s後會爆炸,當遇到‘4‘時,爆炸倒計時會重設為6s。問最短能幾步走出來,不能就輸出-1。

關鍵思想:由於規模很小,簡單BFS即可,因為有折返的情況,所以二維的vis數組是不夠的,可以擴充到三維。或者及時return,因為time是在減少的,所以層數不會太深。另外走過4後再走4是沒什麼效果的。

代碼如下:

#include <iostream>#include <algorithm>#include <queue>using namespace std;int MAP[10][10];int dir[4][2]={0,1,1,0,0,-1,-1,0};int T,N,M;int sx,sy;struct node{    int x,y;    int step,time;};int BFS(){    queue<node>q;    q.push({sx,sy,0,6});    node nw,nt;    while(!q.empty()){        nw=q.front();        q.pop();        if(MAP[nw.x][nw.y]==3){            return nw.step;        }        for(int i=0;i<4;i++){            nt.x=nw.x+dir[i][0],nt.y=nw.y+dir[i][1];            nt.step=nw.step+1,nt.time=nw.time-1;            if(nt.x>=1&&nt.x<=N&&nt.y>=1&&nt.y<=M&&nt.time>0&&MAP[nt.x][nt.y]){                if(MAP[nt.x][nt.y]==4)nt.time=6,MAP[nt.x][nt.y]=0;                q.push(nt);            }        }    }    return -1;}int main(){    scanf("%d",&T);    while(T--){        scanf("%d%d",&N,&M);         for(int i=1;i<=N;i++){            for(int j=1;j<=M;j++){                scanf("%d",&MAP[i][j]);                if(MAP[i][j]==2)sx=i,sy=j;            }        }        printf("%d\n",BFS());    }        return 0;} 

 

HDU 1072 [Nightmare] BFS

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.