链接:http://poj.org/problem?id=2243

题意:给定棋盘上的两个位置a,b,计算马从a跳到b最少需要多少步。

思路:要注意象棋中是马走日。然后就用bfs求最小步数。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<string>
#include<cmath>
#include<algorithm>
#include<map>
using namespace std;


int flag[9][9];
map<char,int> m;
int sx,sy,ex,ey,mins;
int dir[8][2]={{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}};
struct point
{
    int x,y,step;
};
queue<point> q;

void bfs(point s)
{
    bool f=0;
    q.push(s);
    flag[sx][sy]=1;
    while(!q.empty())
    {
        int x,y;
        point t=q.front();
        q.pop();
        for(int i=0;i<8;i++)
        {
            x=t.x+dir[i][0];
            y=t.y+dir[i][1];
            if(x<1 || y<1 || x>8 || y>8 || flag[x][y])
               continue;
            flag[x][y]=1;
            point p;
            p.x=x;p.y=y;p.step=t.step+1;
            q.push(p);
            if(x==ex && y==ey)
            {
                 mins=p.step;
                 f=1;
                 break;
            }
        }
    }
    if(!f) mins=0;
}
int main()
{
    for(int i=1;i<=8;i++)
        m['a'+i-1]=i;
    char a,b;
    while(~scanf("%c%d %c%d",&a,&sy,&b,&ey))
    {
        getchar();
        sx=m[a];
        ex=m[b];
        point s;
        s.x=sx;s.y=sy;s.step=0;
        memset(flag,0,sizeof(flag));
        bfs(s);
        printf("To get from %c%d to %c%d takes %d knight moves.\n",a,sy,b,ey,mins);
    }
    return 0;
}

人生真是无趣啊。。。叹叹

 

 

 posted on 2013-05-21 20:36  ∑求和  阅读(205)  评论(0编辑  收藏  举报