玄关
查看原帖
玄关
1054021
114_Hzh_AK_NOIP_514楼主2024/7/1 21:31
#include <bits/stdc++.h>
using namespace std;
struct node
{
	int x,y,step;
}t,u;
queue <node> q;
int n,m,sx,sy,ex,ey;
char mapp[200][200];
bool book[200][200];
int d[8][2]={{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{-1,2},{1,-2},{-1,-2}};
void bfs(int x,int y,int step)
{
	q.push({x,y,step});
	book[x][y]=1;
	while(!q.empty())
	{
		t=q.front();
		q.pop();
		if(t.x==ex && t.y==ey)
		{
			cout << t.step;
			return;
		}
		for(int i=0;i<8;i++)
		{
			int nx=t.x+d[i][0];
			int ny=t.y+d[i][1];
			if(nx>n || ny>m || nx<1 || ny<1) continue;
			if(book[nx][ny]==0 && mapp[nx][ny]!='*')
			{
				q.push({nx,ny,t.step+1});
				book[nx][ny]=1;
			}
		}
	}
}
int main()
{
	cin >> n >> m;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			cin >> mapp[i][j];
			if(mapp[i][j]=='K')
			{
				sx=i;
				sy=j;
			}
			if(mapp[i][j]=='H')
			{
				ex=i;
				ey=j;
			}
		}
	}
	bfs(sx,sy,1);
	return 0;
}

2024/7/1 21:31
加载中...