原题链接: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;
}