UVa 439 Knight Moves

#include<stdio.h>
#define N 8
int vis[N][N];
int step[N][N];
int dx[8] = {1,2,2,1,-1,-2,-2,-1};
int dy[8] = {2,1,-1,-2,-2,-1,1,2};

int bfs(int x, int y, int target)
{
    int front = 0, rear = 0, u, d;
    int q[70];
    u = N * x + y;
    if(u == target) return 0;
    step[x][y] = 0;
    q[rear++] = u;
    while(front < rear)
    {
        u = q[front++];
        x = u/N;
        y = u%N;
        for(d = 0; d < 8; d++)
        {
            int nx = x + dx[d], ny = y + dy[d];
            if(nx >= 0 && nx < N && ny >= 0 && ny < N && vis[nx][ny] == 0)
            {
                if(nx * N + ny == target) return step[x][y] + 1;
                q[rear++] = nx * N + ny;
                vis[nx][ny] = 1;
                step[nx][ny] = step[x][y] + 1;
            }
        }
    }
}

void ReadInput()
{
    char start[3], end[3];
    while(scanf("%s%s", start, end) == 2)
    {
        int x = start[0] - 'a';
        int y = start[1] - '1';
        int ex = end[0] - 'a';
        int ey = end[1] - '1';
        memset(vis, 0, sizeof(vis));
        memset(step, 0, sizeof(step));
        printf("To get from %s to %s takes %d knight moves.\n",start,end,bfs(x,y,ex*N+ey));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值