习题6-4 骑士的移动(Knight Moves, UVa 439)

原题链接:https://vjudge.net/problem/UVA-439
分类:图
备注:简单BFS

代码如下:

#include<cstdio>
#include<queue>
using namespace std;
const int dir[8][2] = { {-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1} };
struct node {
	int px, py;
	int step;
	node(int x, int y) :px(0), py(0), step(0) {
		px = x; py = y; 
	}
};
bool check(int row, int col) {
	if (row < 1 || row>8 || col < 1 || col>8)return false;
	return true;
}
int main(void) {
	char st[5], ed[5];
	while (~scanf("%s%s", st, ed)) {
		int sr = st[1] - '0', sc = st[0] - 'a' + 1;
		int er = ed[1] - '0', ec = ed[0] - 'a' + 1;
		int vised[10][10] = { 0 };
		node head(sr,sc);
		queue<node>q;
		q.push(head);
		while (!q.empty()) {
			head = q.front(); q.pop();
			if (head.px == er && head.py == ec) break;
			for (int i = 0; i < 8; i++) {
				int row = head.px + dir[i][0];
				int col = head.py + dir[i][1];
				if (!check(row, col) || vised[row][col])continue;
				vised[row][col] = 1;
				node next(row, col);
				next.step = head.step + 1;
				q.push(next);
			}
		}
		printf("To get from %s to %s takes %d knight moves.\n", st, ed, head.step);
	}
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JILIN.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值