好像没有判到陷阱
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
const int N=1010;
struct node{
int x,y,step,magic;
};
int n,k,xx,yy;
char a[N][N];
int f[N][N],xy[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
bool mk[N][N];
queue<node> q;
bool check(int x,int y)
{
if(xx>=1 && xx<=n && yy>=1 && yy<=n && a[x][y]!='#') return true;
return false;
}
int bfs(int x,int k)
{
q.push({1,1,0,0});
while(q.size())
{
node tmp=q.front();
q.pop();
if(tmp.x==n && tmp.y==n) return tmp.step;//因为是一层一层搜,所以一定最优
for(int i=0;i<4;i++)
{
xx=tmp.x+xy[i][0];
yy=tmp.y+xy[i][1];
if(check(xx,yy))//能走
{
if(!mk[xx][yy])
{
if(a[xx][yy]=='.')//一定可以走,判断传参的值
{
if(tmp.magic>0) q.push({xx,yy,tmp.step+1,tmp.magic-1});
else q.push({xx,yy,tmp.step+1,0});
mk[xx][yy]=1;
}else if(a[xx][yy]=='X' && tmp.magic>0){//陷阱,只有magic状态可以走
q.push({xx,yy,tmp.step+1,tmp.magic-1});
mk[xx][yy]=1;
}else{//吃到道具
q.push({xx,yy,tmp.step+1,k});
mk[xx][yy]=1;
}
}else if(a[xx][yy]!='%' && tmp.magic>0) q.push({xx,yy,tmp.step+1,tmp.magic-1});//如果曾经到过,只有有道具的时候才能再走一次,而且不能再走到道具上,因为不会再获得了
}
}
}
return -1;
}
int main()
{
cin>>n>>k;
for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) cin>>a[i][j];
mk[1][1]=1;
cout<<bfs(n,k)<<endl;
return 0;
}