典型的bfs
技巧在于设置了G[x][y]来进行剪枝,减少了运行时间与空间。即如果在某一点,已经有大于当前的查克拉的路线,就不再继续走这一点。
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
int const maxn=205;
int G[maxn][maxn];
char g[maxn][maxn];
int beginx,beginy,endx,endy;
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
struct Point{
int x,y,chak,times;
Point(int x_,int y_,int chak_,int times_):x(x_),y(y_),chak(chak_),times(times_){}
};
int main(){
int m,n,total;
cin>>m>>n>>total;
cin.get();
for(int i=0;i<m;i++){
cin.getline(g[i],maxn);
for(int j=0;j<n;j++){
if(g[i][j]=='@')
{
beginx=i;
beginy=j;
}
if(g[i][j]=='+'){
endx=i;
endy=j;
}
G[i][j]=-1;
}
}
G[beginx][beginy]=total;
queue<Point> p;
p.push(Point(beginx,beginy,total,0));
int ans=1<<30;
while(!p.empty()){
Point temp=p.front();
if(temp.x==endx&&temp.y==endy){
ans=temp.times;
break;
}
for(int i=0;i<4;i++){
int tx=temp.x+dx[i];
int ty=temp.y+dy[i];
if(tx>=0 && tx<m && ty>=0 && ty<n && temp.chak>G[tx][ty]){
if(g[tx][ty]=='#' && temp.chak>0){
p.push(Point(tx,ty,temp.chak-1,temp.times+1));
G[tx][ty]=temp.chak-1;
}
else if(g[tx][ty]=='*' || g[tx][ty]=='+'){
p.push(Point(tx,ty,temp.chak,temp.times+1));
G[tx][ty]=temp.chak;
}
}
}
p.pop();
}
if(ans!=1<<30) cout<<ans;
else cout<<-1;
}