1. 程式人生 > >【BFS】鳴人與佐助

【BFS】鳴人與佐助

bsp struct 全部 main pac pri image iostream cnblogs

總時間限制:
1000ms
內存限制:
65536kB
描述

佐助被大蛇丸誘騙走了,鳴人在多少時間內能追上他呢?

技術分享

已知一張地圖(以二維矩陣的形式表示)以及佐助和鳴人的位置。地圖上的每個位置都可以走到,只不過有些位置上有大蛇丸的手下,需要先打敗大蛇丸的手下才能到這些位置。鳴人有一定數量的查克拉,每一個單位的查克拉可以打敗一個大蛇丸的手下。假設鳴人可以往上下左右四個方向移動,每移動一個距離需要花費1個單位時間,打敗大蛇丸的手下不需要時間。如果鳴人查克拉消耗完了,則只可以走到沒有大蛇丸手下的位置,不可以再移動到有大蛇丸手下的位置。佐助在此期間不移動,大蛇丸的手下也不移動。請問,鳴人要追上佐助最少需要花費多少時間?

輸入
輸入的第一行包含三個整數:M,N,T。代表M行N列的地圖和鳴人初始的查克拉數量T。0 < M,N < 200,0 ≤ T < 10
後面是M行N列的地圖,其中@代表鳴人,+代表佐助。*代表通路,#代表大蛇丸的手下。
輸出
輸出包含一個整數R,代表鳴人追上佐助最少需要花費的時間。如果鳴人無法追上佐助,則輸出-1。
樣例輸入
樣例輸入1
4 4 1
#@##
**##
###+
****

樣例輸入2
4 4 2
#@##
**##
###+
****
樣例輸出
樣例輸出1
6

樣例輸出2
4
參考代碼
///最短路用廣搜,全部解用深搜
#include <iostream>
#include 
<cstdio> #include <queue> using namespace std; int mx,my; char c[202][202]; int vis[202][202][11]; int dir1[4]={-1,1,0,0}; int dir2[4]={0,0,-1,1}; struct naruto{//鳴人的狀態 int x,y; int ch;//查克拉 int time; }; queue <naruto> que; int bfs(int sx,int sy,int ch); int main() { int M,N,T; scanf(
"%d%d%d",&M,&N,&T); getchar();///!!!!!!!!! for(int i=1;i<=M;i++){ for(int j=1;j<=N;j++){ scanf("%c",&c[i][j]); if(c[i][j]==@){ mx=i; my=j; vis[i][j][T]=1; } } getchar(); } ///把邊界當作墻 for(int i=0;i<=N+1;++i) c[0][i]=c[M+1][i]=!; for(int i=0;i<=M+1;++i) c[i][0]=c[i][N+1]=!; printf("%d\n",bfs(mx,my,T)); return 0; } int bfs(int sx,int sy,int ch){ //往隊列裏塞第一個元素 naruto tm; tm.x=sx; tm.y=sy; tm.ch=ch; tm.time=0; que.push(tm); while(!que.empty()){ tm=que.front(); if(c[tm.x][tm.y]==+){ return tm.time; } que.pop(); //遍歷四個方向 for(int i=0;i<4;i++){ int nx=tm.x+dir1[i]; int ny=tm.y+dir2[i]; if((c[nx][ny]==#&&tm.ch>0)||c[nx][ny]==*||c[nx][ny]==+){ naruto tmp; tmp.x=nx; tmp.y=ny; if(c[nx][ny]==#) tmp.ch=tm.ch-1; else tmp.ch=tm.ch; tmp.time=tm.time+1; if(vis[nx][ny][tmp.ch]==0){ que.push(tmp); vis[nx][ny][tmp.ch]=1; } } } } //找不到佐助就返回-1 return -1; }

【BFS】鳴人與佐助