P2802 回家 84分求助
#include<bits/stdc++.h>
using namespace std;
int a[11][11],b[11][11],h[11][11];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int n,m,sx,sy,ex,ey,fx,fy;
queue<int> q1,q2;
int main() {
cin>>n>>m;
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
cin>>a[i][j];
if(a[i][j]==2) {
sx=i; sy=j;
}if(a[i][j]==3) {
ex=i; ey=j;
}
}
}
h[sx][sy]=6;
q1.push(sx); q2.push(sy);
while(!q1.empty()) {
fx=q1.front(); fy=q2.front();
q1.pop(); q2.pop();
for(int i=0;i<4;i++) {
int nx=fx+dx[i];
int ny=fy+dy[i];
if(nx>=1&&nx<=n && ny>=1&&ny<=m && b[nx][ny]==0 && a[nx][ny]!=0 && h[fx][fy]>1) {
q1.push(nx); q2.push(ny);
b[nx][ny]=b[fx][fy]+1;
if(a[nx][ny]==4)h[nx][ny]=6;
else h[nx][ny]=max(h[fx][fy]-1,h[nx][ny]);
}
}
}
if(b[ex][ey]==0)cout<<"-1";
else cout<<b[ex][ey];
}