10分求助
查看原帖
10分求助
981639
huabuyan楼主2024/6/8 09:42
#include<iostream>
#include<queue>
using namespace std;
struct node{
	int x,y,s;
};
int a,b;
int dx[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1};
char l[155][155];
bool v[155][155];
int n,m;
queue<node>q;
node t;
int kx,ky,hx,hy;
int main(){
	cin>>n>>m;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			cin>>l[i][j];
			if(l[i][j]=='K')
			{
				kx=i;
				ky=j;
			}
			if(l[i][j]=='H'){
				hx=i;
				hy=j;
			}
		}
	}
	t.x=kx;
	t.y=ky;
	t.s=0;
	q.push(t);
	while(!(q.empty()))
	{
		node h;
		h.x=q.front().x;
		h.y=q.front().y;
		h.s=q.front().s;
		if(h.x==hx&&h.y==hy)
		{
			cout<<h.s;
			return 0;
		}
		for(int i=0;i<8;i++)
		{
			int tx=h.x+dx[i];
			int ty=h.y+dy[i];
			if(tx>=0&&tx<n&&ty>=0&&ty<m&&!(v[tx][ty]))
			{
				v[tx][ty]=1;
				t.x=tx;
				t.y=ty;
				t.s=h.s+1;
				q.push(t);
			}
		}
		q.pop();
	}
	return 0;
}
2024/6/8 09:42
加载中...