標籤:思想 代碼 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