习题 6-4 UVA 439 Knight Moves 骑士的移动
  gSHLoS4ND9Hs 2023年11月02日 25 0


题意很简单:

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

思路:

简单的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;
}




【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  Fwc2AKebEVGe   2023年11月02日   37   0   0 #define#includei++
  wD98WYW8hiWJ   2023年11月20日   21   0   0 #include
  EhkezVjvcUv6   2023年11月02日   40   0   0 #includei++测试数据
  v0MZS93bOvwU   2023年11月02日   36   0   0 #include
  PVcilKyJJTzb   2023年11月02日   58   0   0 unix硬件平台c语言
  Mqh2iumZ9USt   2023年11月02日   30   0   0 #includei++ios
gSHLoS4ND9Hs