UVa 439 - Knight Moves

/*  思路:
    1、BFS遍历,不必遍历全部
    注意点:
    1、8*8的棋盘格,骑士的走法与象棋中的马走法相同
*/
#include <cstdio>
#include <cstring>
const int MAX = 8;
int visit[MAX][MAX];
int dist[MAX][MAX];
const int dir_x[] = {-1, -2, -2, -1, 1, 2, 2, 1};
const int dir_y[] = {-2, -1, 1, 2, 2, 1, -1, -2};
const int DIR = sizeof(dir_x) / sizeof(dir_x[0]);
int st_y,st_x,ed_y,ed_x;


int qu_x[MAX*MAX];
int qu_y[MAX*MAX];


void bfs()
{
    int front=0, rear=0;
    dist[st_x][st_y] = 0;
    if(st_x == ed_x && st_y == ed_y) return; //found
    visit[st_x][st_y] = 1;
    qu_x[rear]=st_x; qu_y[rear++]=st_y;
    while(front < rear) {
        st_x = qu_x[front]; st_y = qu_y[front++];
        if(st_x == ed_x && st_y == ed_y) return; //found
        for(int i=0; i<DIR; i++) {
            int t_x = st_x + dir_x[i];
            int t_y = st_y + dir_y[i];
            if(!visit[t_x][t_y] && t_x>=0 && t_x<MAX && t_y>=0 && t_y<MAX) {
                dist[t_x][t_y] = dist[st_x][st_y] + 1;
                if(t_x == ed_x && t_y == ed_y) return; //found
                visit[t_x][t_y] = 1;
                qu_x[rear]=t_x; qu_y[rear++]=t_y;
            }
        }
    }
}


int main ()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    #endif
    char st[4];
    char ed[4];
    while(scanf("%s%s", st, ed)==2) {
        st_y = st[0] - 'a';
        st_x = st[1] - '1';
        ed_y = ed[0] - 'a';
        ed_x = ed[1] - '1';
        memset(visit, 0, sizeof(visit));
        bfs();
        printf("To get from %s to %s takes %d knight moves.\n", st, ed, dist[ed_x][ed_y]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值