Knight Moves

 Knight Moves

 

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■□
 骑士从A到B的走法
 */
# include<iostream>
# include<queue>
using namespace std;
char chr1[3],chr2[3];
int vis[9][9],Min;
int Dir[8][2]={{2,1},{-2,1},{2,-1},{-2,-1},{1,2},{1,-2},{-1,2},{-1,-2}};
struct node
{
    int row,col,step;
}p;
void bfs()
{
        queue<node>C;//用队列可以解决
        p.row=chr1[1]-'1';
        p.col=chr1[0]-'a';
        p.step=0;
        vis[p.row][p.col]=1;
        C.push(p);
        while(!C.empty())
        {
            node a=C.front();
            C.pop();
            if(a.row==(chr2[1]-'1')&&a.col==(chr2[0]-'a'))
            {
                if(a.step<Min)Min=a.step;
                return;
            }
           p=a;
           for(int i=0;i<8;i++)//八个方向搜索
           {
               node q;//这里想了好一会儿,如果不node q,p就相当于自加了,会出错
        q.row=p.row+Dir[i][0];
        q.col=p.col+Dir[i][1];
            if(!vis[q.row][q.col]&&q.row>=0&&q.row<8&&q.col>=0&&q.col<8)
            {
                vis[q.row][q.col]=1;
                q.step=p.step+1;
                C.push(q);

            }    
           }
        }
}
int main()
{
    while(cin>>chr1>>chr2)
    {
        Min=9999999;
    memset(vis,0,sizeof(vis));
    bfs();
    cout<<"To get from "<<chr1<<" to "<<chr2<<" takes "<<Min<<" knight moves."<<endl;
    }
    return 0;
}

 

posted on 2012-05-15 20:15  即为将军  阅读(316)  评论(0)    收藏  举报

导航