习题 6-4 UVA 439 Knight Moves 骑士的移动

题意很简单:

问一个马从起点走到终点最短步数。

思路:

简单的bfs,输入得到起点终点,直接用队列走就可以了!

#include<cstdio>
#include<queue>
using namespace std;
int sx,sy,gx,gy;
const int INF = 1e8;
int idx[10][10];
const int dx[] = {-1,-2,-2,-1,1,2,2,1};
const int dy[] = {-2,-1,1,2,2,1,-1,-2};
typedef pair<int,int>P;
int main()
{
    char s1[5],s2[5];
    while(scanf("%s%s",s1,s2) == 2){
        for (int i = 1 ; i <= 8; ++i)
            for (int j = 1; j <= 8; ++j)
                idx[i][j]=INF;
        queue<P>q;
        sy=s1[1]-48;sx=8-(s1[0]-'a');
        gy=s2[1]-48;gx=8-(s2[0]-'a');
        q.push(P(sx,sy));
        idx[sx][sy]=0;
        while(!q.empty()){
            P p = q.front();q.pop();
            if (p.first == gx && p.second == gy)break;
            for (int i = 0; i < 8; ++i){
                int nx = p.first + dx[i];
                int ny = p.second + dy[i];
                if (nx >= 1 && nx <= 8 && ny >= 1 && ny <= 8 && idx[nx][ny] == INF){
                    q.push(P(nx,ny));
                    idx[nx][ny] = idx[p.first][p.second] + 1;
                }
            }
        }
        printf("To get from %s to %s takes %d knight moves.\n",s1,s2,idx[gx][gy]);
    }
    return 0;
}
    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/aozil_yang/article/details/50704450
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞