马的遍历

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;

const int MAXN = 400 + 5;
int n, l;
int xx, yy;
int map[MAXN][MAXN];
int dx[] = { 0, -1, -2, -1, -2, 1, 2, 1, 2}; 	// 方向 
int dy[] = { 0, -2, -1, 2, 1, -2, -1, 2, 1};
int vis[MAXN][MAXN];			// 存步数,最后要输出的 
struct Node
{
	int x;						// 坐标 
	int y;	
	int step;					// 步数 
};
struct Node queue[MAXN * MAXN];

void bfs(int tx, int ty)		// 搜! 
{
	int head = 0, tail = 1, nx, ny;
	queue[tail].x = tx;
	queue[tail].y = ty;
	queue[tail].step = 0;
	vis[tx][ty] = queue[tail].step;
	while(head < tail)
	{
		head++;
		for(int i = 1; i <= 8; i++)		// 枚举 
		{	
			nx = queue[head].x + dx[i];
			ny = queue[head].y + dy[i];
			if(nx >= 1 && nx <= n && ny >= 1 && ny <= l && vis[nx][ny] == -1)//判定范围 
			{
				tail++;
				queue[tail].x = nx;					
				queue[tail].y = ny;
				queue[tail].step = queue[head].step + 1;
				vis[nx][ny] = queue[tail].step;

			}
					
		}
	}
}

int main()
{
	cin >> n >> l;
	cin >> xx >> yy;
	for(int i = 1; i <= n; i++)		//	初始化 
		for(int j = 1; j <= l; j++)
			vis[i][j] = -1; 		 
			
	bfs(xx, yy);
	for(int i = 1; i <= n; i++)		//	输出,注意格式 
	{
		for(int j = 1; j <= l; j++)
			printf("%-5d",vis[i][j]);
		cout << endl;	
	}	
	return 0;
 } 
原文地址:https://www.cnblogs.com/go-alltheway/p/13691857.html