题意:
已知一张地图(以二维矩阵的形式表示)以及佐助和鸣人的位置。地图上的每个位置都可以走到,只不过有些位置上有大蛇丸的手下,需要先打败大蛇丸的手下才能到这些位置。鸣人有一定数量的查克拉,每一个单位的查克拉可以打败一个大蛇丸的手下。假设鸣人可以往上下左右四个方向移动,每移动一个距离需要花费 11 个单位时间,打败大蛇丸的手下不需要时间。如果鸣人查克拉消耗完了,则只可以走到没有大蛇丸手下的位置,不可以再移动到有大蛇丸手下的位置。佐助在此期间不移动,大蛇丸的手下也不移动。请问,鸣人要追上佐助最少需要花费多少时间?中文题面就是nice!
解题思路:
BFS:
与常规搜索不同,可以用三维数组去储存一个点是否访问过。即
vis[i][j][t]第(i,j)个点在剩余查克拉为t时是否访问过
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
#define LL long long
#define MT(a,b) memset(a,b,sizeof(a))
const int mod=10007;
const int maxn=1e5+5;
const int ONF=-0x3f3f3f3f;
const int INF=0x3f3f3f3f;
bool vis[205][205][15];
char mp[205][205];
int m,n,t;
int xx[]={-1,1,0,0};
int yy[]={0,0,-1,1};
struct node{
int x,y,t;
int step;
}qwe[maxn<<2];
LL bfs(int stx,int sty){
node tmp{},head{};
MT(vis, false);
vis[stx][sty][t]=true;
tmp.x=stx,tmp.y=sty,tmp.t=t,tmp.step=0;
queue<node>q;
q.push(tmp);
while (!q.empty()){
head=q.front();
q.pop();
for (int i=0;i<4;i++){
int tx=head.x+xx[i],ty=head.y+yy[i];
if (tx<0||ty<0||tx>=m||ty>=n) continue;
if (vis[tx][ty][head.t]) continue;
if (mp[tx][ty]=='+'){
return head.step+1;
}
if (mp[tx][ty]=='*'){
tmp.t=head.t,tmp.x=tx,tmp.y=ty,tmp.step=head.step+1;
vis[tx][ty][tmp.t]=true;
q.push(tmp);
}
if (mp[tx][ty]=='#'){
tmp.x=tx,tmp.y=ty,tmp.step=head.step+1;
tmp.t=head.t-1;
if (vis[tx][ty][tmp.t]||tmp.t<0) continue;
vis[tx][ty][tmp.t]=true;
q.push(tmp);
}
}
}
return -1;
}
int main (){
scanf("%d%d%d",&m,&n,&t);
for (int i=0;i<m;i++)
scanf("%s",mp[i]);
for (int i=0;i<m;i++)
for (int j=0;j<n;j++)
if (mp[i][j]=='@') printf("%lld\n",bfs(i,j));
return 0;
}
关于dfs,可以用。但是要判断走到一个点是否是最短距离,很麻烦,要加很多限制条件。bfs自带的特性就是第一次走到一个点,此时走的路程就是最短的路程。