九度oj-1365:贝多芬第九交响曲

#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;

typedef struct step
{
	int x;
	int y;
	int cost;
}step;

int mark[101][101];

int next[][2] = 
{
	-2,1,
	-1,2,
	1,2,
	2,1,
	-2,-1,
	-1,-2,
	1,-2,
	2,-1
};

int startx,starty,endx,endy,n;
queue<step> que;

int bfs()
{
	int i,x,y,cost;
	step tmp1,tmp2;
	while(!que.empty())
	{
		tmp1 = que.front();
		x = tmp1.x;
		y = tmp1.y;
		cost = tmp1.cost;

		que.pop();

		for(i=0; i<8; i++)
		{
			if(mark[x+next[i][0]][y+next[i][1]] == 0 && x+next[i][0] >= 1 && x+next[i][0] <= n && y+next[i][1] >= 1 && y+next[i][1] <= n)
			{
				tmp2.x = x+next[i][0];
				tmp2.y = y+next[i][1];
				tmp2.cost = cost+1;

				que.push(tmp2);
				mark[tmp2.x][tmp2.y] = 1;     //不要忘记标记

				if(tmp2.x == endx && tmp2.y == endy)
					return tmp2.cost;
			}
		}

	}

	return -1;
}
int main()
{
	int ans;
	step tmp;

	while(scanf("%d", &n) != EOF)
	{

		memset(mark,0,sizeof(mark));
		while(!que.empty())
			que.pop();

		scanf("%d%d%d%d", &startx, &starty, &endx, &endy);

		if(startx == endx && starty ==  endy)   //考虑重合的情况
			printf("0\n");
		else
		{
			mark[startx][starty] = 1;
			tmp.x = startx;
			tmp.y = starty;
			tmp.cost = 0;
			que.push(tmp);
			ans = bfs();
			
			printf("%d\n", ans);
		}

	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值