其他分享
首页 > 其他分享> > Knight Moves

Knight Moves

作者:互联网

 

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.

题意:类似于马走日,可以往8个方向走,问最少步数。经典bfs 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
using namespace std;
int gx,gy;
int dx[8]={-2,-2,-1,-1,1,1,2,2},dy[8]={1,-1,2,-2,2,-2,1,-1};
struct node{
    int x,y;
    int step;
};
int bfs(int x,int y){
    int i;
    queue<node>q;
    node st,ed;
    st.step=0;
    st.x=x;
    st.y=y;
    q.push(st);
    while(!q.empty()){
        st=q.front();
        q.pop();
        for(i=0;i<8;i++){
            ed.x=st.x+dx[i];
            ed.y=st.y+dy[i];
            if(ed.x>0&&ed.x<=8&&ed.y>0&&ed.y<=8){
                ed.step=st.step+1;
                if(ed.x==gx&&ed.y==gy){
                    //cout<<ed.x<<' '<<ed.y<<endl;
                    return ed.step;
                }
                q.push(ed);
            }
        }
    }
    return -1;
}
int main(){
    int s2;
    char s1,g1;
    int sx,sy;
    while(~scanf("%c%d %c%d",&s1,&s2,&g1,&gy)){
        getchar();
        sx=s1-'a'+1;
        sy=s2;
        gx=g1-'a'+1;
        if(sx==gx&&sy==gy){
            printf("To get from %c%d to %c%d takes 0 knight moves.\n",s1,s2,g1,gy);
        }else{
            int s=bfs(sx,sy);
            printf("To get from %c%d to %c%d takes %d knight moves.\n",s1,s2,g1,gy,s);
        }
        
    }
    
    return 0;    
}

 

标签:moves,takes,get,int,Knight,a1,knight,Moves
来源: https://blog.csdn.net/wys5wys/article/details/99168458