坑点:注意用vis数组标记走过的路时,要用三维数组(不仅要标记走过的路,还要标记血量)
原因:可能直接走这一格要直接死,但是绕一下再走这一格就不会死,不能直接这个格子走过了就不走了,判定该格子走没走过还要判断血量
#include <bits/stdc++.h>
using namespace std;
const int N=100;
char c[N][N];
int n,m,ans;
int vis[N][N][N];
int dis[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
struct node{
int x,y,cnt=0,res;
};
bool inline check(int x,int y){
return x>=0&&x<n&&y>=0&&y<m;
}
queue<node>q;
void bfs(int x,int y,int cnt,int res){
node now;
now.x=x,now.y=y,now.cnt=cnt,now.res=res;
q.push(now);
int min=11000;
while(!q.empty()){
now=q.front();
q.pop();
for(int i=0;i<4;i++){
int xx=now.x+dis[i][0];
int yy=now.y+dis[i][1];
// cout<<xx<<" "<<yy;
if(xx==n-1&&yy==m-1){
if(now.cnt<min&&now.res>0){
min=now.cnt;
//cout<<xx<<" "<<yy<<" "<<now.res<<endl;
}
//cout<<now.cnt<<endl;
}
if(check(xx,yy)&&!vis[xx][yy][now.res]&&c[xx][yy]!='*'){
node mp;
if(c[xx][yy]!='.'){
int op=c[xx][yy]-'0';
// cout<<" "<<op<<endl;
if(now.res-op>0){
mp.x=xx,mp.y=yy,mp.cnt=now.cnt+1;
mp.res=now.res-op;
q.push(mp);
vis[xx][yy][mp.res]=1;
}
else continue;
}
else {
mp.x=xx,mp.y=yy,mp.cnt=now.cnt+1,mp.res=now.res;
vis[xx][yy][mp.res]=1;
q.push(mp);
}
}
}
}
if(min==11000)cout<<"-1"<<endl;
else cout<<min<<endl;
return ;
}
int main(){
cin>>n>>m>>ans;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>c[i][j];
}
}
vis[0][0][ans]=1;
bfs(0,0,1,ans);
return 0;
}