Knight Moves UVA - 439(BFS最短路)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/leekerian/article/details/86901705
#include <iostream>
#include <queue>
#include <cstring>

using namespace std;

int vis[11][11];
int mx[8]={1,2,2,1,-1,-2,-2,-1};
int my[8]={2,1,-1,-2,-2,-1,1,2};

struct node
{
    int x,y,m;
    node(int _x,int _y,int _m){x=_x,y=_y,m=_m;}
};

queue<node> q;

int sx,sy,ex,ey;
int bfs()
{
    vis[sx][sy]=1;
    q.push(node(sx,sy,0));
    while(!q.empty())
    {
        node t=q.front();q.pop();
        if(t.x==ex&&t.y==ey) return t.m;
        for(int i=0;i<8;i++)
        {
            int x,y;
            x=t.x+mx[i];
            y=t.y+my[i];
            if(x==ex&&y==ey) return t.m+1;
            if(x>=1&&x<=8&&y>=1&&y<=8&&!vis[x][y])
            {
                q.push(node(x,y,t.m+1));
                vis[x][y]=1;
            }
        }
    }
    return 0;
}
int main()
{
    char str[4],str1[4];
    while(scanf("%s%s",str,str1)==2)
    {
        while(!q.empty())
            q.pop();
        memset(vis,0,sizeof(vis));
        sx=str[0]-'a'+1;
        sy=str[1]-'0';
        ex=str1[0]-'a'+1;
        ey=str1[1]-'0';
        printf("To get from %s to %s takes %d knight moves.\n",str,str1,bfs());
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/leekerian/article/details/86901705