传送门UVa 439 & SDU 1372 - Knight Moves
题意:国际象棋中的骑士跳,给一个起点和终点,求最小步数。
刚开始看不懂怎么跳。。我捉急的知识面。。。。
百度了一下,骑士跳就是中国象棋中马的跳法。
参考了shuangde800的解题报告,很好的思路。
引用一下他的说明
分析:
这题也是一道十分经典的搜索入门题。 由于题目是指定象棋中马的开始位置,与目标位置, 要求马以最少的步数走到目标位置。 凡是求最短步数的,一般用BFS做比较好。
求步数时, 有个小技巧, 开个vis数组,初始化为0, 然后这个用来记录走的步数,而不仅仅是用来标记是否走过。具体见代码
刚才被上一道题搞得欲仙欲死,到最后也没搞出来,现在脑子还是混乱的。哎。。。。
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
struct node
{
int x, y;
};
char start[3], target[3];
queue<node> qu;
int vis[10][10];
int dir[8][2] = {{-2, -1}, {-2, 1}, {2, -1}, {2, 1}, {-1, 2}, {-1, -2}, {1, 2}, {1, -2}};
void BFS();
int main()
{
//freopen("input.txt", "r", stdin);
while (~scanf("%s %s%*c", start, target))
{
memset(vis, 0, sizeof(vis));
BFS();
}
return 0;
}
void BFS()
{
node now;
now.x = start[0] - 'a';
now.y = start[1] - '1';
qu.push(now);
vis[now.x][now.y] = 1;
while (!qu.empty())
{
if (qu.front().x == target[0] - 'a' && qu.front().y == target[1] - '1')
{
printf("To get from %s to %s takes %d knight moves.\n", start, target, vis[qu.front().x][qu.front().y] - 1);
while (!qu.empty())
qu.pop();
return;
}
for (int i = 0; i < 8; i++)
{
int dx = qu.front().x + dir[i][0];
int dy = qu.front().y + dir[i][1];
if (dx >= 0 && dx < 8 && dy >= 0 && dy < 8 && !vis[dx][dy])
{
vis[dx][dy] = vis[qu.front().x][qu.front().y] + 1;
node temp;
temp.x = dx, temp.y = dy;
qu.push(temp);
}
}
qu.pop();
}
}