参考代码:
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
struct node{int x, y, step, ticket;node(int a, int b, ll c, int d){x=a, y=b, step=c, ticket=d;}
};
queue<node> q;
bool vis[1005][1005];
int n, k;bool checkL(int x, int y)
{return (x >= 0 && x < n && y >= 0 && y < n) ? true : false;
}int main()
{ios::sync_with_stdio(false);cin >> n >> k;string s[1005];for(int i = 0; i < n; i++)cin >> s[i];q.push(node(0, 0, 0, 0));int cnx[4]={1,-1,0,0};int cny[4]={0,0,1,-1};int newx, newy;while(!q.empty()){node top = q.front();q.pop();if(top.x == n-1 && top.y == n-1){cout << top.step;return 0;}for(int i = 0; i < 4; i++){newx = top.x + cnx[i];newy = top.y + cny[i];if(checkL(newx, newy) && s[newx][newy] != '#'){if(s[newx][newy] == '%'){q.push(node(newx, newy, top.step+1, k));s[newx][newy] = '#';}else if(top.ticket > 0){q.push(node(newx, newy, top.step+1, top.ticket-1));vis[newx][newy] = true;}else if(s[newx][newy] == '.' && vis[newx][newy] == false){q.push(node(newx, newy, top.step+1, 0));vis[newx][newy] = true;}}}}return 0;
}