思路:BFS,是先更新步数然后再看是否入队
#pragma GCC optimize(2)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<stack>
#include<iomanip>
#include<cstring>
#include<time.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=2e6+10;
const int M=1e5+10;
const int inf=0x3f3f3f3f;
const int maxx=2e5+7;
const double eps=1e-6;
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
ll lcm(ll a,ll b)
{
return a*(b/gcd(a,b));
}
template <class T>
void read(T &x)
{
char c;
bool op = 0;
while(c = getchar(), c < '0' || c > '9')
if(c == '-')
op = 1;
x = c - '0';
while(c = getchar(), c >= '0' && c <= '9')
x = x * 10 + c - '0';
if(op)
x = -x;
}
template <class T>
void write(T x)
{
if(x < 0)
x = -x, putchar('-');
if(x >= 10)
write(x / 10);
putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
ll res=1%p;
while(b)
{
if(b&1)
res=res*a%p;
a=1ll*a*a%p;
b>>=1;
}
return res;
}
int n, m,k;
int dir[8][2]={
{
-1,2},{
-2,1},{
-1,-2},{
-2,-1},{
1,2},{
2,1},{
1,-2},{
2,-1}};
char mp[205][205];
int vis[205][205];
int step[205][205];
int sx,sy,ex,ey;
queue<PII> q;
int cnt=0;
void bfs()
{
int ans=0;
memset(step,inf,sizeof step);
vis[sx][sy]=1;
q.push({
sx,sy});
step[sx][sy]=0;
while(!q.empty())
{
ans++;
PII now=q.front();q.pop();
for(int i=0;i<8;i++)
{
int xx=now.first+dir[i][0];
int yy=now.second+dir[i][1];
if(xx<1||xx>n||yy<1||yy>m)continue;
if(mp[xx][yy]=='*')continue;
step[xx][yy]=min(step[now.first][now.second]+1,step[xx][yy]);
if(!vis[xx][yy]){
vis[xx][yy]=1;
q.push({
xx,yy});
}
if(xx==ex&&yy==ey){
printf("%d",step[xx][yy]);
return ;
}
}
}
}
int main()
{
scanf("%d%d",&m,&n);
for(int i=1;i<=n;i++)
{
getchar();
for(int j=1;j<=m;j++)
{
scanf("%c",&mp[i][j]);
if(mp[i][j]=='K') sx=i,sy=j;
if(mp[i][j]=='H') ex=i,ey=j;
}
}
bfs();
return 0;
}