1. 程式人生 > 其它 >試題 演算法訓練 跳馬(BFS)

試題 演算法訓練 跳馬(BFS)

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>//佇列標頭檔案
using namespace std;

int dir[8][2] = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, 2}, {1, -2}, {2, 1}, {2, -1}};//馬移動的8個方位
int map[15][15], sx, sy, tar_x, tar_y;//棋盤和起點終點
bool vis[15][15];//記錄點

struct node {//馬的座標
	int x;
	int y;
};

bool inmap(int x, int y) {//確定馬是否在棋盤上
	return x >= 1 && x <= 8 && y >= 1 && y <= 8;
}

void bfs(int x, int y) {
	vis[x][y] = 1;
	queue<node> q;//建立佇列
	q.push({x, y});
	int step = 0;
	map[x][y] = step;
	while (!q.empty()) {
		node now = q.front();
		for (int i = 0; i < 8; i++) {//8個方向
			int nx = now.x + dir[i][0];
			int ny = now.y + dir[i][1];
			if (inmap(nx, ny) && !vis[nx][ny]) {//判斷是否在棋盤上以及是否經過
				vis[nx][ny] = 1;
				map[nx][ny] = step;
				q.push({nx, ny});
			}
		}
		q.pop();
	}
}

int main() {
	cin >> sx >> sy >> tar_x >> tar_y;
	bfs(sx, sy);
	for (int i = 1; i <= 8; i++) {
		for (int j = 1; j <= 8; j++)
			cout << map[i][j] << " ";
		cout << endl;
	}
	cout<<map[tar_x][tar_y];
	return 0;
}