1 题目编号:1015
2 题目内容:
e2 e4<br>a1 b2<br>b2 c3<br>a1 h8<br>a1 h7<br>h8 a1<br>b1 c3<br>f6 f6<br>
To get from e2 to e4 takes 2 knight moves.<br>To get from a1 to b2 takes 4 knight moves.<br>To get from b2 to c3 takes 2 knight moves.<br>To get from a1 to h8 takes 6 knight moves.<br>To get from a1 to h7 takes 5 knight moves.<br>To get from h8 to a1 takes 6 knight moves.<br>To get from b1 to c3 takes 1 knight moves.<br>To get from f6 to f6 takes 0 knight moves.<br>
3 解题思路形成过程:就是在一个8*8的棋盘中给定两个点,行号用英文字母给定,列用数字给定,现在要问你的是一个骑士如何以最少的不少步数走到另外一个点。BFS,八个方向加上判定是否越界。
4 代码:#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
int c[9][9];
int dir[8][2] = { { -2, -1 }, { -2, 1 }, { -1, 2 }, { 1, 2 }, { 2, 1 }, { 2, -1 }, { 1, -2 }, { -1, -2 } };
typedef struct
{
int x, y, count;
}node;
node start, finish;
int bfs()
{
memset(c, 0, sizeof(c));
node pre, cur;
start.count = 0;
queue<node> q;
q.push(start);
c[start.x][start.y] = 1;
while (!q.empty())
{
pre = q.front();
q.pop();
if (pre.x == finish.x&&pre.y == finish.y)
return pre.count;
for (int i = 0; i < 8; i++)
{
cur.x = pre.x + dir[i][0];
cur.y = pre.y + dir[i][1];
if (cur.x<1 || cur.x>8 || cur.y<1 || cur.y>8)continue;
if (c[cur.x][cur.y] == 1)continue;
c[cur.x][cur.y] = 1;
cur.count = pre.count + 1;
q.push(cur);
}
}
return -1;
}
int main()
{
char row, end;
int col, ed;
int min;
while (scanf("%c", &row) != EOF)
{
scanf("%d", &col);
getchar();
scanf("%c%d", &end, &ed);
getchar();
start.x = row - 'a' + 1;
start.y = col;
finish.x = end - 'a' + 1;
finish.y = ed;
if (start.x == finish.x&&start.y == finish.y)
min = 0;
else min = bfs();
printf("To get from %c%d to %c%d takes %d knight moves.\n", row, col, end, ed, min);
}
return 0;
}