1185 : Knight Moves
| Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
|---|---|---|---|---|---|
| | 1s | 8192K | 620 | 289 | Standard |
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 Specification
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 Specification
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.
这一题刚开始我没看懂,以为很简单,只要坐标加减运算就好了,后来想到原来骑士走的是“日”字,广度优先搜索解决
#include<iostream>
#include<cstring>
using namespace std;
int map[9][9];
int vis[9][9];
struct pos
{
int x,y;
};
int move[8][2]={{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}};
int main()
{
string s1,s2;
pos qu[100];
while(cin>>s1>>s2)
{
int x1=s1[0]-'a'+1,y1=s1[1]-'0';
int x2=s2[0]-'a'+1,y2=s2[1]-'0';
memset(vis,0,sizeof(vis));
memset(map,0,sizeof(map));
int front=0,rear=0;
vis[x1][y1]=1;
qu[rear].x=x1;qu[rear].y=y1;
rear++;
while(front<rear)
{
pos u=qu[front++];
if(u.x==x2&&u.y==y2) break;
for(int i=0;i<8;i++)
{
pos st;
st.x=u.x+move[i][0];
st.y=u.y+move[i][1];
if(st.x>=1&&st.x<=8&&st.y>=1&&st.y<=8&&!vis[st.x][st.y])
{
vis[st.x][st.y]=1;
qu[rear++]=st;
map[st.x][st.y]=map[u.x][u.y]+1;
}
}
}
/* for(int i=1;i<=8;i++)
{
for(int j=1;j<=8;j++)
{
cout<<map[i][j]<<" ";
}
cout<<endl;
}
*/
cout<< "To get from "<<s1<<" to "<<s2<<" takes "<<map[x2][y2]<<" knight moves."<<endl;
}
return 0;
}
本文介绍了一种使用广度优先搜索算法解决国际象棋中骑士从一个格子移动到另一个格子的最短路径问题的方法。通过具体示例展示了如何计算骑士移动所需的最少步数。
691

被折叠的 条评论
为什么被折叠?



