UVa 439 Knight Moves (bfs)

题目链接:~( ̄▽ ̄~)(~ ̄▽ ̄)~


水过~

#include <stdio.h>
#include <string.h>
int map[10][10], used[10][10], X1 = 0, Y1 = 0, X2 = 0, Y2 = 0, sum = 0;
int dir[8][2] = {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};
typedef struct
{
	int x, y, count;
}node;
node step, quene[105];
void bfs()
{
	int i = 0, front = 0, rear = 0,  x= 0, y = 0, fx = 0, fy = 0, count = 0;
	quene[rear++] = step;
	while(front<rear)
	{
		step = quene[front++];
		x = step.x; y = step.y; count = step.count;
		for(i = 0; i<8; i++)
		{
			fx = x+dir[i][0]; fy = y+dir[i][1];
			if(fx == X2 && fy == Y2)
			{
				sum = count+1;
				return ;
			}
			if(!used[fx][fy] && fx>0 && fx<=8 && fy>0 && fy<=8)
			{
				step.x = fx; step.y = fy; step.count = count+1;
				quene[rear++] = step;
				used[fx][fy] = 1;
			}
		}
	}
}
int main()
{
	while(scanf("%c %d %c %d",&Y1,&X1,&Y2,&X2) != EOF)
	{
		memset(used, 0, sizeof(used));
		getchar();
		Y1 = Y1-'a'+1; Y2 = Y2-'a'+1;
		step.x = X1; step.y = Y1; step.count = 0;
		used[X1][Y1] = 1;
		if(X1 == X2 && Y1 == Y2)
			sum = 0;
		else
			bfs();
		printf("To get from %c%d to %c%d takes %d knight moves.\n", Y1+'a'-1, X1, Y2+'a'-1, X2, sum);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值