UVA 439 Knight Moves


题意:8*8的棋盘,给定一个起点和终点,求马至少需要多少步可以从起点跳到终点。


思路:bfs模板。注意坐标判重,判断坐标越界。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define Clean(x,y) memset(x,y,sizeof(x))
const int dx[8] = {-2,-2,-1,-1,1,1,2,2};
const int dy[8] = {1,-1,2,-2,2,-2,1,-1};


int st_x,st_y,ed_x,ed_y;
bool flag[10][10];
char temp[20];
int main()
{
    while( gets(temp) )
    {
        queue<int> step,x,y;
        st_x = temp[0] - 'a' + 1;
        ed_x = temp[3] - 'a' + 1;
        st_y = temp[1] - '0';
        ed_y = temp[4] - '0';
        Clean(flag,true);
        flag[st_x][st_y]  = false;
        x.push(st_x);
        y.push(st_y);
        step.push(0);
        int tx,ty,xx,yy,ss;
        while( !x.empty() )
        {
            xx = x.front();
            yy = y.front();
            ss = step.front();
            x.pop();
            y.pop();
            step.pop();
            if ( xx == ed_x && yy == ed_y )
            {
                printf("To get from %c%c to %c%c takes %d knight moves.\n",temp[0],temp[1],temp[3],temp[4],ss);
                break;
            }
            for(int i = 0; i < 8; i++ )
            {
                tx = xx + dx[i];
                ty = yy + dy[i];
                if (  tx>=1 && tx<=8 && ty>=1 && ty<=8 && flag[tx][ty] )
                {
                    flag[tx][ty] = false;
                    x.push(tx);
                    y.push(ty);
                    step.push(ss+1);
                }
            }
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值