P1443 马的遍历

#include 
#include 
using namespace std;
#define M 400
int arr[M + 5][M + 5];
typedef struct Node {
	int x, y;
} Node;
//将马能走的8个方向封装成一个二维数组
int dir[8][2] = {
	{2, 1}, {2, -1}, {-2, 1}, {-2, -1},
	{1, 2}, {-1, 2}, {1, -2}, {-1, -2}};
void fun(int x, int y, int n, int m) {
	Node node;
	node.x = x, node.y = y;
	arr[x][y] = 0;
	queue q;
	q.push(node);
	//广搜
	while (!q.empty()) {
		int indx = q.front().x, indy = q.front().y;
		q.pop();
		for (int i = 0; i < 8; i++) {
			int x1 = indx + dir[i][0];
			int y1 = indy + dir[i][1];
			if (x1 < 1 || x1 > n)  continue;
			if (y1 < 1 || y1 > m)  continue;
			//遍历过了就直接跳过,因为是广搜,所以当前一定不如之前更优
			if (arr[x1][y1] != -1) continue;
			arr[x1][y1] = arr[indx][indy] + 1;
			Node n;
			n.x = x1, n.y = y1;
			q.push(n);
		}
	}
	return;
}
int main() {
	int n, m, x, y;
	cin >> n >> m >> x >> y;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			//先每行初始化-1
			arr[i][j] = -1;
		}
	}
	fun(x, y, n, m);
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << arr[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}

P1443 马的遍历_第1张图片

你可能感兴趣的:(算法题,算法,c++,数据结构)