O - 上一个题的加强版
Crawling in process... Crawling failed Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Description
A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy.
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
Input
The input will contain one or more test cases. Each test case consists of one line containing two squares separated by one space. A square is a string consisting of a letter (a-h) representing the column and a digit (1-8) representing the row on the chessboard.
Output
For each test case, print one line saying "To get from xx to yy takes n knight moves.".
Sample Input
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
Sample Output
To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.
题目大意:这道题是建立在poj2488的基础上的,我们已经知道了knight的移动规则,这道题是给了你起点和终点的位置坐标,问你从起点到终点所需要的最小步数。
思路分析:我的第一直觉就是使用bfs,bfs的实现主要是依靠队列来进行实现 ,这时候队列中元素的类型就显得犹为重要,这在我看来是使用bfs所必须要首先考虑
的问题,对于本题而言,在进行bfs时所需要记录的一个是x,一个是y,还有一个是step,所以我选择了结构体类型,如果需要记录的只有两个元素的话使用pair类型
也是可以的:还要有两点需要注意一下,一个是输出格式,一定要一致,否则会一wa到底,另外一个就是题目说明有多组测试实例,在输出一组答案后一定记得把队列
清空,否则会出现错误。
代码:#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;
int maps[10][10];
int f[8][2]={{-2,-1},{-2,1},{-1,2},{-1,-2},{1,2},{1,-2},{2,-1},{2,1}};
struct nod
{
int x;
int y;
int step;
};
queue<nod> bfs;
int main()
{
char a,b;
int c,d;
while(cin>>a>>c>>b>>d)
{
nod m,n,p;
memset(maps,0,sizeof(maps));
int tx=b-'a',ty=d-1;
m.x=a-'a',m.y=c-1,m.step=0;
bfs.push(m);
while(!bfs.empty())
{
p=bfs.front();
if(p.x==tx&&p.y==ty)
{
printf("To get from %c%d to %c%d takes %d knight moves.\n",a,c,b,d,p.step);
break;
}
for(int i=0;i<8;i++)
{
n.x=p.x+f[i][0];
n.y=p.y+f[i][1];
n.step=p.step+1;
if(n.x>=0&&n.x<=7&&n.y>=0&&n.y<=7&&!maps[n.x][n.y])
{
maps[n.x][n.y]=1;
bfs.push(n);
}
}
bfs.pop();
}
while(!bfs.empty())
{
bfs.pop();
}
}
return 0;
}
奋斗!前进!