Knight Moves(BFS)

Question:题目详情(http://vjudge.net/contest/135927#problem/A)
题目大意:在一个棋盘上横坐标为1~8,纵坐标为a~g,给你一个起点高一个终点,让你用中国象棋的马走日算出起点到终点的最短步数
解题思路:这就是一道简单的bfs的题,只是跟以往的不同的是这次是“马走日”,其余的没什么不同

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <queue>
using namespace std;
struct node{
    int x,y,num;
}a[100];
int vis[10][10],b[8][2]={1,2,1,-2,-1,2,-1,-2,2,1,-2,1,2,-1,-2,-1};  //实现,马走日
int main(){
    char ch1,ch2;
    int x1,x2,y1,y2;
    queue<node> q;
    while(cin>>ch1>>x1>>ch2>>x2){
        y1=(int )ch1-'a'+1;
        y2=(int )ch2-'a'+1;
        memset(vis,0,sizeof(vis));
        int ans=0,flag=0;
        while(!q.empty())
            q.pop();
        q.push(node{x1,y1,0});
        vis[x1][y1]=1;
        while(!q.empty()){
            node t=q.front();
            q.pop();
            if(t.x==x2&&t.y==y2){
                    ans=t.num;
                    flag=1;
                    break;
                }
            for(int i=0;i<8;i++){
                int tx=t.x+b[i][0];
                int ty=t.y+b[i][1];
                if(tx<1||tx>8||ty<1||ty>8||vis[tx][ty])
                    continue;
                q.push(node{tx,ty,t.num+1});
                vis[tx][ty]=1;
            }
            if(flag==1)
                break;
        }
        printf("To get from %c%d to %c%d takes %d knight moves.\n",ch1,x1,ch2,x2,ans);
    }
    return 0;
}

体会:上述代码没什么用仔细说的,都是常规做法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值