习题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;
}
发布了104 篇原创文章 · 获赞 97 · 访问量 4515

猜你喜欢

转载自blog.csdn.net/TK_wang_/article/details/105354110