Poj 1915 骑士遍历

不解释的BFS。

#include <stdio.h>
#include <string.h>
#define MAXM (300+5)

typedef struct {
    int x;
    int y;
    int d;
}Node;

Node queue[MAXM*MAXM];
int front,rear;
int dir[8][2]={ {-2,1},{-1,2},{1,2},{2,1}, {2,-1},{1,-2},{-1,-2},{-2,-1} };
int visit[MAXM][MAXM];
int M;

int Q_empty()
{
    if( rear == front ) return 1;
    return 0;
}

Node Q_front()
{
    if( Q_empty() ) return ;
    return queue[front];
}

void Q_pop()
{
    front = (front+1) % (MAXM*MAXM);
}

void Q_push( Node cur )
{
    queue[rear]= cur;
    rear = (rear+1) % (MAXM*MAXM) ;
}

int in_map(Node cur)
{
	if( cur.x>=0 && cur.x <M && cur.y>=0 && cur.y <M)
		return 1;
	return 0;
}

int bfs( Node from , Node to )
{
    int i;
    Node a,cur;

    if( from.x == to.x && from.y == to.y ) return 0;

    from.d=0;
    Q_push(from);
    visit[from.x][from.y]=1;
    while( !Q_empty() )
    {
        a = Q_front();
        Q_pop();

        cur.d= a.d + 1;
        for( i=0 ; i < 8 ; i++)
        {
            cur.x= a.x + dir[i][0];
            cur.y= a.y + dir[i][1];
            if( in_map(cur) && !visit[cur.x][cur.y] )
			{
				if( cur.x==to.x && cur.y==to.y )
					return cur.d;
				Q_push(cur);
				visit[cur.x][cur.y]=1;
			}
        }
    }
    return -1;
}

int main()
{
    int n;
    int i;
    Node from,to;
//   freopen("test.in","r",stdin);
    while(~scanf("%d",&n))
    {
        for(i=0;i<n;i++)
        {
            scanf("%d",&M);

            memset(visit,0,sizeof(visit));
            front=rear=0;

            scanf("%d%d",&from.x,&from.y);
            scanf("%d%d",&to.x,&to.y);
            printf("%d\n",bfs(from,to));
        }
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值