马的遍历

AC代码:

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N = 510;
int ans[N][N],n,m,x,y;
const int dx[8] = { -1,-2,-2,-1,1,2,2,1 };
const int dy[8] = { 2,1,-1,-2,2,1,-1,-2 };
typedef pair<int, int>PII;//开一个可以存两个int的变量,用于存坐标(x,y)
queue<PII> q;

void bfs()
{
	//队列非空
	while (!q.empty())
	{
		auto now = q.front();//记录下当前队列首元素
		q.pop();//将队列的首元素弹出
		int d = ans[now.first][now.second];
		for (int i = 0; i < 8; i++)
		{
			int ax = now.first + dx[i];
			int ay = now.second + dy[i];
			//如果跨过边界了或者当前位置访问过了,就直接continue不管
			if (ax<1 || ax>n || ay<1 || ay>m || ans[ax][ay] != -1)
				continue;
			ans[ax][ay] = d + 1;//在上一次的距离加上1
			q.push({ ax,ay });//继续入队列
		}
	}
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			printf("%-5d", ans[i][j]);
		}
		puts("");
	}
}

int main(void)
{
	cin >> n >> m >> x >> y;
	memset(ans, -1,sizeof ans);//没有访问就标记为-1
	ans[x][y] = 0;//从[x,y]走的,当前格子步数就是0
	q.push({ x,y });//将[x,y]坐标加入到队列当中
	bfs();
	return 0;
}

posted @ 2023-08-24 22:28  Hayaizo  阅读(7)  评论(0编辑  收藏  举报