1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
#include<bits/stdc++.h>
#define x first #define y second
using namespace std;
typedef pair<int, int> PII;
const int N=200, M=N*N;
int n, m; char g[N][N]; bool st[N][N]; PII q[M]; PII pre[N][N];
void bfs(int sx, int sy){ int hh=0, tt=0; q[0]={sx, sy}; st[sx][sy]=true;
memset(pre, -1, sizeof pre);
int dx[8]={1, 1, 2, 2, -1, -1, -2, -2}, dy[8]={2, -2, 1, -1, 2, -2, 1, -1};
while(hh<=tt){ PII t=q[hh++];
for(int i=0;i<8;i++){ int x=t.x+dx[i], y=t.y+dy[i];
if(x<0 || x>=n || y<0 || y>=m) continue; if(st[x][y]) continue; if(g[x][y]=='*') continue;
q[++tt]={x, y}; st[x][y]=true;
pre[x][y]=t; } } }
void work(){ scanf("%d%d", &m, &n);
int x0, y0, x1, y1; for(int i=0;i<n;i++) for(int j=0;j<m;j++){ scanf(" %c", &g[i][j]); if(g[i][j]=='K') x0=i, y0=j; if(g[i][j]=='H') x1=i, y1=j; }
bfs(x1, y1);
int cnt=0; PII end(x0, y0); while(true){ cnt++; if(end.x==x1 && end.y==y1) break; end=pre[end.x][end.y]; }
printf("%d", cnt-1); }
int main(){ work(); return 0; }
|