已知一张地图(以二维矩阵的形式表示)以及佐助和鸣人的位置。地图上的每个位置都可以走到,只不过有些位置上有大蛇丸的手下,需要先打败大蛇丸的手下才能到这些位置。鸣人有一定数量的查克拉,每一个单位的查克拉可以打败一个大蛇丸的手下。假设鸣人可以往上下左右四个方向移动,每移动一个距离需要花费1个单位时间,打败大蛇丸的手下不需要时间。如果鸣人查克拉消耗完了,则只可以走到没有大蛇丸手下的位置,不可以再移动到有大蛇丸手下的位置。佐助在此期间不移动,大蛇丸的手下也不移动。请问,鸣人要追上佐助最少需要花费多少时间?
样例输入1 4 4 1 #@## **## ###+ **** 样例输入2 4 4 2 #@## **## ###+ ****
样例输出1 6 样例输出2 4
#include
#include
#include
#include
using namespace std;
const int maxn = 210;
char g[maxn][maxn];
int G[maxn][maxn];
int m, n, w;
int sr, sc, er, ec;
int dr[4] = {0, 1, 0, -1};
int dc[4] = {1, 0, -1, 0};
struct Node
{
int r, c, w, t;
Node(int r, int c, int w, int t) : r(r), c(c), w(w), t(t) {}
};
int main()
{
scanf("%d%d%d", &m, &n, &w);
for(int i = 0; i < m; i++)
{
scanf("%s", g[i]);
for(int j = 0; j < n; j++)
{
G[i][j] = -1; //每个格子的查克拉数量初始化为-1,因为鸣人没有查克拉的时候(即为0),依然可以走这个格子
if(g[i][j] == '@')
sr = i, sc = j;
if(g[i][j] == '+')
er = i, ec = j;
}
}
queue q;
q.push(Node(sr, sc, w, 0));
G[sr][sc] = w;
int ans = 1 << 30;
while(!q.empty())
{
Node p = q.front();
if((p.r == er && p.c == ec))
{
ans = p.t;
break;
}
for(int i = 0; i < 4; i++)
{
int tr = p.r+dr[i];
int tc = p.c+dc[i];
if(tr >= 0 && tr < m && tc >= 0 && tc < n )
{
if(g[tr][tc] == '#' && p.w > 0)
{
q.push(Node(tr, tc, p.w-1, p.t+1));
G[tr][tc] = p.w-1;
}
else if(g[tr][tc] == '*' || g[tr][tc] == '+')
{
q.push(Node(tr, tc, p.w, p.t+1));
G[tr][tc] = p.w;
}
}
}
q.pop();
}
if(ans != 1 << 30) printf("%d\n", ans);
else printf("-1");
return 0;
}
#include
#include
#include
#include
using namespace std;
const int maxn = 210;
char g[maxn][maxn];
int G[maxn][maxn];
int m, n, w;
int sr, sc, er, ec;
int dr[4] = {0, 1, 0, -1};
int dc[4] = {1, 0, -1, 0};
struct Node
{
int r, c, w, t;
Node(int r, int c, int w, int t) : r(r), c(c), w(w), t(t) {}
};
int main()
{
scanf("%d%d%d", &m, &n, &w);
for(int i = 0; i < m; i++)
{
scanf("%s", g[i]);
for(int j = 0; j < n; j++)
{
G[i][j] = -1; //ÿ¸ö¸ñ×ӵIJé¿ËÀÊýÁ¿³õʼ»¯Îª-1£¬ÒòΪÃùÈËûÓвé¿ËÀµÄʱºò£¨¼´Îª0£©£¬ÒÀÈ»¿ÉÒÔ×ßÕâ¸ö¸ñ×Ó
if(g[i][j] == '@')
sr = i, sc = j;
if(g[i][j] == '+')
er = i, ec = j;
}
}
queue q;
q.push(Node(sr, sc, w, 0));
G[sr][sc] = w;
int ans = 1 << 30;
while(!q.empty())
{
Node p = q.front();
if((p.r == er && p.c == ec))
{
ans = p.t;
break;
}
for(int i = 0; i < 4; i++)
{
int tr = p.r+dr[i];
int tc = p.c+dc[i];
if(tr >= 0 && tr < m && tc >= 0 && tc < n && p.w>G[tr][tc]) //***
{
if(g[tr][tc] == '#' && p.w > 0)
{
q.push(Node(tr, tc, p.w-1, p.t+1));
G[tr][tc] = p.w-1;
}
else if(g[tr][tc] == '*' || g[tr][tc] == '+')
{
q.push(Node(tr, tc, p.w, p.t+1));
G[tr][tc] = p.w;
}
}
}
q.pop();
}
if(ans != 1 << 30) printf("%d\n", ans);
else printf("-1");
return 0;
}