【POJ】2243Knight Moves(BFS)
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;
}