紫书 UVA439

/*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 <bits/stdc++.h>

using namespace std;
int m[9][9];
int dir[8][2]= {{-2,1},{-1,2},{1,2},{2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}};
struct node
{
    int x,y;
    node(int a,int b):x(a),y(b) {}
};
int d[9][9];
int vis[9][9];
char a,b;
int a1,b1;
void bfs(node a)
{
    queue<node> q;
    q.push(a);
    //cout<<a.x<<a.y;
    memset(vis,0,sizeof(vis));
    memset(d,0,sizeof(d));
    vis[a.x][a.y]=1;
    while(!q.empty())
    {
        node p=q.front();
        int x0=p.x;
        int y0=p.y;
        if(p.x==b1&&p.y==b-'a'+1)
            return;
        q.pop();
        for(int i=0; i<8; i++)
        {
            int x1=x0+dir[i][0];
            int y1=y0+dir[i][1];
          //  cout<<x1<<" "<<y1<<endl;;
            if(x1>0&&x1<=8&&y1>0&&y1<=8&&!vis[x1][y1])
            {
                node t(x1,y1);
                d[x1][y1]=d[x0][y0]+1;
                //cout<<d[x1][y1]<<" ";
                if(x1==b1&&y1==(b-'a'+1))
                    return ;
                vis[x1][y1]=1;
                q.push(t);
            }
        }
    }

}
int main()
{

    while(scanf("%c%d %c%d",&a,&a1,&b,&b1)!=EOF)
    {
        getchar();//此处 一定要清除上一次输入的'\n'
        bfs(node(a1,a-'a'+1));
        cout<<"To get from "<<a<<a1<<" to "<<b<<b1<<" takes "<<d[b1][b-'a'+1]<<" knight moves."<<endl;
    }
    return 0;
}


posted @ 2018-05-02 17:31  MCQ  阅读(96)  评论(0编辑  收藏  举报