UVa 439-Knight Moves

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=380
非常简单基础的一道BFS题。不同一般的BFS的是,马的移动方式。国际象棋马的走法和中国象棋一样,都是走日字。不过国际象棋总棋子是走格子,而中国象棋是走交叉点。下惯了中国象棋的我还是很不习惯这一点的。不过搞清楚了马的走法就好办了。我设置的马的八个遍历方向是按照顺时针来的。以下是代码:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<queue>
using namespace std;

struct Vertex
{
    int r;
    int c;
    int level;
    Vertex(){};
    Vertex(int _r,int _c,int _level):r(_r),c(_c),level(_level){};
};

int map[8][8];
char str1[3];
char str2[3];
int visited[8][8];
int dir[8][2]={{-1,-2},{-1,2},{1,2},{1,-2},{-2,-1},{-2,1},{2,1},{2,-1}};//遍历的方向,即马的走法
Vertex e;

int BFS(int r,int c)
{
    int i;
    queue<Vertex> qu;
    visited[r][c]=1;
    qu.push(Vertex(r,c,0)); 
    while(!qu.empty())
    {
        Vertex v=qu.front(); 
        qu.pop();
        if(v.r==e.r&&v.c==e.c) return v.level;
        for(i=0;i<8;i++)
        {
            int r1=v.r+dir[i][0];
            int c1=v.c+dir[i][1];
            if(r1>=0 && r1<8 && c1>=0 && c1<8)
            {
                if(visited[r1][c1]==0)
                {
                    qu.push(Vertex(r1,c1,v.level+1));
                    visited[r1][c1]=1;
                }
            }
        }
    }
}

int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);

    while(scanf("%s%s",str1,str2)!=EOF)
    {
        memset(map,0,sizeof(map));
        memset(visited,0,sizeof(visited));
        //将字符转化成数字坐标,第一个字符是列数,第二个字符是行数
        e.r=str2[1]-49;
        e.c=str2[0]-97;
        int l=BFS(str1[1]-49,str1[0]-97);
        printf("To get from %s to %s takes %d knight moves.\n",str1,str2,l);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值