uva 439 - Knight Moves

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

int vis[10][10], ans[100];;
int step[10][3]= {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{-2,1},{2,-1},{-2,-1}};
int bfs(int x1, int y1, int x2, int y2)
{
    int front = 0, rear = 1, list[100][3];
    list[front][0] = x1;
    list[front][1] = y1;
    vis[x1][y1] = 1;
    ans[front] = 0;
    while(front < rear)
    {
        for(int i = 0; i < 8; i++)
        {
            int x = step[i][0] + list[front][0], y = step[i][1] + list[front][1];
            if(x>0 && x<=8 && y>0 && y<=8 && !vis[x][y])
            {
                if(x == x2 && y == y2) return ans[front]+1;
                list[rear][0] = x;
                list[rear][1] = y;
                ans[rear++] = ans[front] + 1;
                vis[x][y] = 1;
            }
        }
        front++;
    }
    return 0;
}
int main()
{
    char s1[3], s2[3];
    while(cin >> s1 >> s2)
    {
        memset(vis, 0, sizeof(vis));
        memset(ans, 0, sizeof(ans));
        int count = bfs(s1[1]-'0', s1[0]-'a'+1, s2[1]-'0', s2[0]-'a'+1);
        printf("To get from %s to %s takes %d knight moves.\n", s1, s2, count );
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值