c++ bfs求最短路径长度
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
#define fi first
#define se second
const int N=155;
int n, m;
char G[N][N];
int dist[N][N];
const int dirs[8][2]={{-2,-1}, {-2,1}, {-1,-2}, {-1,2}, {1,-2}, {1,2}, {2, -1}, {2, 1}};
int main(){
memset(dist, -1, sizeof dist);
memset(G, 0x00, sizeof G);
cin>>m>>n;
for(int i=0; i<n; ++i) cin>>G[i];
int posx=-1, posy=-1;
for(int i=0; i<n; ++i)
for(int j=0; j<m; ++j)
if(G[i][j]=='K') {posx=i, posy=j;}
function<int(int, int)> bfs=[&](int posx, int posy){
queue<PII> q;
q.push({posx, posy});
dist[posx][posy]=0;
while(!q.empty()){
int x=q.front().fi;
int y=q.front().se;
q.pop();
for(int i=0; i<8; ++i){
int nx=x+dirs[i][0];
int ny=y+dirs[i][1];
if(0<=nx&&nx<n&&0<=ny&&ny<m&&dist[nx][ny]==-1){
if(G[nx][ny]=='H') return dist[x][y]+1;
else{
q.push({nx, ny});
dist[nx][ny]=dist[x][y]+1;
}
}
}
}
return -1;
};
cout<<bfs(posx, posy)<<endl;
return 0;
}