马的遍历

马的遍历_第1张图片

#include
#include
#include
#include
using namespace std;
int dx[] = { 1,1,2,2,-1,-1,-2,-2 };
int dy[] = { 2,-2,1,-1,2,-2,1,-1 };
int n, m;//棋盘规格
bool b[402][402];
int sign[401][401];
struct node
{
	int x;
	int y;
	int step;
};
node a;

void bfs(node a)
{
	queue q;
	node p, temp;
	q.push(a); int i;
	b[a.x][a.y] = false;
	sign[a.x][a.y] = 0;
	while (!q.empty())
	{
		p = q.front(); q.pop();
		temp = p;//保护p
		for (i = 0; i < 8; i++)
		{
			p = temp;
			p.x = p.x + dx[i]; p.y = p.y + dy[i];
			if (p.x<1 || p.x>n || p.y < 1 || p.y >m)
			{
				continue;
			}
			else
			{
				if (b[p.x][p.y] == false)continue;
				b[p.x][p.y] = false;
				p.step++;
				sign[p.x][p.y] = p.step;
				q.push(p);
			}
		}

	}
}


int main()
{

	scanf("%d%d", &n, &m);
	scanf("%d%d", &a.x, &a.y);
	a.step = 0;//开始点的坐标
	node temp = a;//保护a;
	int i, j;
	memset(b, true, sizeof(b));
	memset(sign, -1, sizeof(sign));
	bfs(a);
	for (i = 1; i <= n; i++)
	{
		for (j = 1; j <= m; j++)
		{
			printf("%-5d", sign[i][j]);
		}
		cout << endl;
	}
	return 0;
}

你可能感兴趣的:(算法题目)