搜索:zoj 1091 Knight Moves (广搜)

【转】http://blog.csdn.net/zxy_snow/article/details/5741881

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int state[9][9];
int count[9][9];
int Queue[100000];
int step[8][2] = {1,2, 1,-2, -1,2, -1,-2, 2,1, 2,-1, -2,1, -2,-1};
int head,tail;
int push(int x)
{
    Queue[head++] = x;
}
int pop(void)
{
    return Queue[tail++];
}
int Qempty(void)
{
    if( head == tail )
        return 1;
    return 0;
}
void init(void)
{
    head = 0; tail = 0;
    memset( state,0,sizeof(state) );
    memset( count,0,sizeof(count) );
    memset( Queue,0,sizeof(Queue) );
}
int main(void)
{
    int a,b,x,y,temp,tempa,tempx,ta,tx,i;
    char ch1,ch2,n;
    while( scanf("%c%d %c%d%c",&ch1,&x,&ch2,&y,&n)!=EOF ) //这点很纠结,因为有个回车,不再输入一个回车的话,会错
    {
        init();
        a = ch1 - 'a' + 1;
        b = ch2 - 'a' + 1;
        push(a); push(x);
        state[a][x] = 1;
        while( !Qempty() )
        {
            tempa = pop();
            tempx = pop();
            if( tempa == b && tempx == y)
                break;
            for(i=0; i<8; i++)//8个方向,用循环一一调用,这点很值得学习!
            {
                ta = tempa + step[i][0];
                tx = tempx + step[i][1];
                if(state[ta][tx] == 0 && ta>=1 && ta<=8 && tx>=1 && tx<=8 )
                {
                    push(ta); push(tx);
                    state[ta][tx] = 1;
                    count[ta][tx] = count[tempa][tempx] + 1;
                }
            }
        }
        printf("To get from %c%d to %c%d takes %d knight moves./n",ch1,x,ch2,y,count[tempa][tempx]);
    }
system("pause");
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值