HDU<1372>/bfs

题目连接

简单bfs搜索


#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int, int> pa;
typedef long long  LL;
int dir[8][2]={2,1,2,-1,-2,1,-2,-1,1,2,1,-2,-1,2,-1,-2};
struct node
{
    int x;
    int y;
    int step;
};
int vis[10][10];//标记数组
int st,sd,et,ed;
queue<node>que;
string c1,c2;
void init()
{
    for(int i=0;i<=8;i++)
        for(int j=0;j<=8;j++)
            vis[i][j]=0;
}
void dfs()
{
    node now,next;
    now.x=st;
    now.y=sd;
    vis[st][sd]=1;
    now.step=0;
    while(!que.empty())
        que.pop();
    que.push(now);
    while(!que.empty())
    {
        now=que.front();
        que.pop();
        if(now.x==et&&now.y==ed)
        {
            cout<<"To get from "<<c1<<" to "<<c2<<" takes "<<now.step<<" knight moves."<<endl;
            break;
        }
        for(int i=0;i<8;i++)
        {

            int X=now.x+dir[i][0];
            int Y=now.y+dir[i][1];
            if(X>=1&&X<=8&&Y>=1&&Y<=8&&!vis[X][Y])
            {
                next.x=X;
                next.y=Y;
                next.step=now.step+1;
                vis[X][Y]=1;
                que.push(next);
            }
        }
    }
}
int main ()
{
    while(cin>>c1>>c2)
    {
        init();
        st=c1[0]-'a'+1;
        sd=c1[1]-'1'+1;
        et=c2[0]-'a'+1;
        ed=c2[1]-'1'+1;
        dfs();
    }
    return 0;
}
posted @ 2016-07-31 19:05  _Mickey  阅读(114)  评论(0编辑  收藏  举报