hdu 1072(BFS) 有炸彈

來源:互聯網
上載者:User

標籤:

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

題目大意是在一個n×m的地圖上,0表示牆,1表示空地,2表示人,3表示目的地,4表示有定時炸彈重啟器。

定時炸彈的時間是6,人走一步所需要的時間是1。每次可以上、下、左、右移動一格。

當人走到4時如果炸彈的時間不是0,可以重新設定炸彈的時間為6。如果人走到3而炸彈的時間不為0時,

成功走出。求人從2走到3的最短時間。

一道典型的搜尋,用的bfs,結構體中開一個step表示要求的時間,也就相當於步數,一個time表示炸彈的時間,

注意的是這裡其實每個點都可以重複訪問,為了求能夠到達的最小時間,4的位置如果必須要走的話其實只走一次

一個炸彈點如果走多次,雖然設定了最大限時但是往返消耗了時間得不償失,好好想想這裡

code

 1 #include<cstdio> 2 #include<queue> 3 #include<cstring> 4 using namespace std; 5 struct point { 6     int x,y; 7     int time,step;//炸彈時間與步數 8 }; 9 int dx[]={1,-1,0,0};10 int dy[]={0,0,1,-1};11 int n,m;12 int visit[10][10],map[10][10];13 int bfs(int sx,int sy)14 {15     int i;16     memset(visit,0,sizeof(visit));17     queue<point>Q;18     point now,next;19     now.x=sx;now.y=sy;20     now.time=6;21     now.step=0;22     visit[now.x][now.y]=1;23     Q.push(now);24     while (!Q.empty())25     {26         now=Q.front();27         Q.pop();28         if (map[now.x][now.y]==3)29             return now.step;30         if (now.time<=1)continue;31         for (i=0;i<4;i++)32         {33             next.x=now.x+dx[i];34             next.y=now.y+dy[i];35             if (next.x<1||next.x>n||next.y<1||next.y>m)continue;36             if (map[next.x][next.y]==0)continue;37             if (visit[next.x][next.y]==1)continue;38             next.step=now.step+1;39             next.time=now.time-1;40             if (map[next.x][next.y]==4)41             {42                 next.time=6;43                 visit[next.x][next.y]=1;//確保只走一次,標記44             }45             Q.push(next);46         }47     }48     return -1;49 }50 int main()51 {52     int t,i,j,sx,sy;53     while (~scanf("%d",&t)){54     while (t--)55     {56         scanf("%d %d",&n,&m);57         for (i=1;i<=n;i++)58         {59             for (j=1;j<=m;j++)60             {61                 scanf("%d",&map[i][j]);62                 if (map[i][j]==2)63                 {64                     sx=i;65                     sy=j;66                 }67             }68         }69         printf("%d\n",bfs(sx,sy));70     }71     }72     return 0;73 }

 

hdu 1072(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.