鸣人和佐助
总时间限制:
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
- 最重的是查克拉剩余量的控制。
- maxk[xx][yy]数组,用来记录查克拉剩余量的最大值。
- 注意条件分类,只要没遇到大蛇丸手下,剩下的就是通路。(前面已经先判断了“+”佐助的位置)。
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
#define inf 0x3f3f3f3f
struct pos{
int x;
int y;
int k;//当前所剩下的查克拉
int t;//花费的时间
pos(int xx, int yy, int kk, int tt) : x(xx), y(yy), k(kk), t(tt) {}
};
char maze[206][206];
int ans, dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int maxk[206][206];//到达当前格子时,所剩查克拉的最大值
int m, n, t;
queue<pos> q;
int judge(int xx,int yy)
{
if(xx < 0 || xx >= m || yy < 0 || yy >= n )
return 1;
else
return 0;
}
void bfs()
{
while (!q.empty())
{
pos now = q.front();
q.pop();
if (maze[now.x][now.y] == '+')
{
ans = now.t;
return;
}
else
{
for (int i = 0; i < 4; i++)
{
int xx = now.x + dir[i][0];
int yy = now.y + dir[i][1];
if (judge(xx,yy)|| maxk[xx][yy] >= now.k)
continue;
if (maze[xx][yy] == '#')//碰到大蛇丸手下
{
if (now.k > 0)//查克拉充足
{
q.push(pos(xx, yy, now.k - 1, now.t + 1));
maxk[xx][yy] = now.k;
}
}
else
{
q.push(pos(xx, yy, now.k, now.t + 1));
maxk[xx][yy] = now.k;
}
}
}
}
}
int main()
{
cin >> m >> n >> t;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cin >> maze[i][j];
maxk[i][j] = -1;//为零的时候也是可以走的,所以初始化为-1
if (maze[i][j] == '@')//找到鸣人的位置
{
q.push(pos(i, j, t, 0));
maxk[i][j] = t;
}
}
}
ans = inf;
bfs ();
if (ans == inf)
{
cout << -1 << endl;
}
else
{
cout << ans << endl;
}
return 0;
}