11:鸣人和佐助
总时间限制:-
描述
-
佐助被大蛇丸诱骗走了,鸣人在多少时间内能追上他呢?
已知一张地图(以二维矩阵的形式表示)以及佐助和鸣人的位置。地图上的每个位置都可以走到,只不过有些位置上有大蛇丸的手下,需要先打败大蛇丸的手下才能到这些位置。鸣人有一定数量的查克拉,每一个单位的查克拉可以打败一个大蛇丸的手下。假设鸣人可以往上下左右四个方向移动,每移动一个距离需要花费1个单位时间,打败大蛇丸的手下不需要时间。如果鸣人查克拉消耗完了,则只可以走到没有大蛇丸手下的位置,不可以再移动到有大蛇丸手下的位置。佐助在此期间不移动,大蛇丸的手下也不移动。请问,鸣人要追上佐助最少需要花费多少时间?
输入
-
输入的第一行包含三个整数:M,N,T。代表M行N列的地图和鸣人初始的查克拉数量T。0 < M,N < 200,0 ≤ T < 10
后面是M行N列的地图,其中@代表鸣人,+代表佐助。*代表通路,#代表大蛇丸的手下。
输出
- 输出包含一个整数R,代表鸣人追上佐助最少需要花费的时间。如果鸣人无法追上佐助,则输出-1。 样例输入
-
样例输入14 4 1#@##**#####+****样例输入24 4 2#@##**#####+****
样例输出
-
样例输出16样例输出24
解题思路:
这道题毋庸置疑bfs,但是里面有好多点需要注意,像走过的的地方其实还可以再走,只要查克拉数量比之前经过该点的数量多,就可以走,不能用传统的标记地图方法。若过不了小龙人,再给你一组数据看看:
输入样例:
10 10 1 @#******** *******### *******##* *******##* *******##* *******##* *******##* *******##* *******##* *******##+
输出样例:
20
若以上样例都通过了,还是没有AC,那就是你代码风格的问题了,小龙人就是在这里栽了个大跟头。
代码实现:
#include <iostream> #include <cstdio> #include <cstring> #include <queue> #include <map> #include <vector> #include <set> #include <cmath> #include <algorithm> using namespace std; const int maxn = 205; char mp[maxn][maxn]; int dis[4][2] = { {-1,0},{1,0},{0,-1},{0,1} }; int cnt[maxn][maxn]; // 记录每个点的查克拉数量; int M, N, T, flag = 0; struct node { int x, y, timee; // 每个点的坐标及到达该点用的时间; }step[40000]; int bfs(int x, int y) { memset( cnt, -1, sizeof(cnt)); int i, j; int num = 0; step[num] = { x, y , 0}; queue<node>q; q.push(step[0]); cnt[x][y] = T; while( !q.empty() ) { node p = q.front(); q.pop(); int nowx = p.x, nowy = p.y, nowcnt = cnt[p.x][p.y], nowtime = p.timee; for( i=0; i<4; i++ ) { int gx = nowx + dis[i][0], gy = nowy + dis[i][1]; if( gx < M && gx >= 0 && gy < N && gy >= 0 && nowcnt > cnt[gx][gy] )
//只有现在的查克拉数量大于下一个点的查克拉数量才能走,这里是难点,多想想; { if( mp[gx][gy] == '*' ) { cnt[gx][gy] = nowcnt; step[++num] = { gx, gy , nowtime+1}; q.push(step[num]); } else if ( mp[gx][gy] == '#' ) { if( nowcnt - cnt[gx][gy] > 1 ) // 只有现在的查克拉数量消灭怪物后大于下个点的查克拉 数量,才可以走,也就是nowcnt-1>cnt[gx][gy]; { cnt[gx][gy] = nowcnt-1; step[++num] = { gx, gy, nowtime+1}; q.push(step[num]); } } else if( mp[gx][gy] == '+') // 出口; return ++nowtime; } } } flag = 1; cout << "-1" <<endl; return 0; } int main() { while(scanf("%d%d%d",&M,&N,&T)!=EOF) { int timen=0; int i, j, x, y; for( i=0; i<M; i++ ) { scanf("%s",mp[i]); } for( i=0; i<=M; i++ ) for( j=0; j<=N; j++ ) if( '@' == mp[i][j] ){ timen = bfs( i, j ); break; } if( flag == 0 ) cout << timen << endl; flag = 0; } return 0; }