Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 15703 | Accepted: 8744 |
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 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.
Source
题目大意: 一个8*8的中国象棋棋牌,给你两个坐标,问你马从起点走到终点最少需要几步.
思路:这个就是基础的BFS了,dfs也是能做的,
告诉你起始位置和终点位置,判断好马走日的那八个方向,
用dist数组表示到某一步的步数, 不用考虑后面是否需要对于某点更新一下最小值,因为一个点,走过了就不会再走一次,更何况一开始保存的就是到某点的最小步数,
代码:
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
#include<algorithm>
#define maxn 9
using namespace std;
int r1,r2,c1,c2;
struct Node
{
int r,c;
Node(int r,int c):r(r),c(c){}
};
int vis[maxn][maxn];
int dist[maxn][maxn];
queue<Node >Q;
int dr[]={-2,-2,-1,-1,1,1,2,2};
int dc[]={-1,1,2,-2,2,-2,1,-1}; //马走日的八个方向
int BFS()
{
if(r1==r2&&c1==c2) return 0;
while(!Q.empty()) Q.pop();
memset(vis,0,sizeof(vis));
vis[r1][c1]=1;
dist[r1][c1]=0;
Q.push(Node(r1,c1));
while(!Q.empty())
{
Node node=Q.front();
Q.pop();
int r=node.r,c=node.c;
for(int d=0;d<8;d++)
{
int nr=r+dr[d];
int nc=c+dc[d];
if(nr>=0&&nr<8 &&nc>=0&&nc<8 &&vis[nr][nc]==0)
{
if(nr==r2&&nc==c2) return dist[r][c]+1;
dist[nr][nc]=dist[r][c]+1;
Q.push(Node(nr,nc));
vis[nr][nc]=1;
}
}
}
return -1;
}
int main()
{
char str1[10],str2[10];
while(scanf("%s%s",str1,str2)==2)
{
r1=str1[1]-'1';
c1=str1[0]-'a';
r2=str2[1]-'1';
c2=str2[0]-'a';
printf("To get from %s to %s takes %d knight moves.\n",str1,str2,BFS());
}
return 0;
}