HDU 1372 Knight Moves (广搜)

时间:2021-02-07 21:47:50

题目链接

Problem 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.

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 file 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.

分析:

题意求是求a点跳到b点。

一开始以为是简单的四个方向,发现步数老是不对,从a1到h8走了十几步,而案例只要6步。此时我就开始想可能不是简单的四个方向,开会仔细的验算案例。

可以看倒数第二个案例,从b1到c3,只要一步。对角线构成的矩形变成了有点”日“的形状,这正是象棋里的马走日。

所以是跳马。众所周知,中国象棋的马可以往八个方向跳。

所以改下方向。把输入弄好。

一个裸BFS。就能求出最小的步数了

代码:

#include <stdio.h>
#include <queue>
#include <string.h>
#include <algorithm>
using namespace std;
int vis[10][10];
int dir[8][2]={{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}}; //马的八个方向
int sx,sy;
struct node
{
int x,y;
int step;
}
;
bool check(int x,int y)
{
if(x>8 ||x<1 ||y>8 ||y<1 ||vis[x][y])
return 0;
return 1;
}
int bfs(int x,int y)
{
node st,ed;
int i;
queue<node>q;
st.x=x;
st.y=y;
st.step=0;
q.push(st);
while(!q.empty())
{
st=q.front();
q.pop();
if(st.x==sx &&st.y==sy)
return st.step;
for(i=0;i<8;i++)
{
ed.x=st.x+dir[i][0];
ed.y=st.y+dir[i][1];
if(!check(ed.x,ed.y))
continue;
ed.step=st.step+1;
vis[ed.x][ed.y]=1;
q.push(ed);
}
}
}
int main()
{
char s[22];
char s1[22];
int x2,y2;
int i,j;
while(scanf("%s%s",s,s1)!=EOF)
{
sx=s1[0]-'a'+1;
sy=s1[1]-'0';
x2=s[0]-'a'+1;
y2=s[1]-'0'; // 控制好输入
// printf("%d %d\n",x2,y2); // 用这个可以检查转为后的坐标
// printf("%d %d\n",sx,sy);
memset(vis,0,sizeof(vis));
vis[x2][y2]=1;
int ans=bfs(x2,y2); //裸BFS
printf("To get from %s to %s takes %d knight moves.\n",s,s1,ans);
}
return 0;
}