试题 算法训练 跳马(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}};
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});
	map[x][y] = 0;
	while (!q.empty()) {
		node now = q.front();
		for (int i = 0; i < 8; i++) {
			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] = map[now.x][now.y] + 1;
				q.push({nx, ny});
			}
		}
		q.pop();
	}
}

int main() {
	cin >> sx >> sy >> tar_x >> tar_y;
	bfs(sx, sy);
	cout << map[tar_x][tar_y];
	return 0;
}
posted @   帝宝单推人!  阅读(168)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示