POJ2243 Knight Moves(BFS)

34 篇文章 0 订阅

题意:

输入两组坐标,输出骑士从一个到另一个最少要几步(骑士走日字)

要点:

标准的BFS题,寻找最短路径,用队列做


15170656Seasonal2243Accepted176K16MSC++1099B2016-02-17 17:36:15
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
using namespace std;
bool visit[20][20];
int dx[8] = { -2, -2, -1, -1, 1, 1, 2, 2 };
int dy[8] = { -1, 1, -2, 2, -2, 2, -1, 1 };
struct node
{
	int x;
	int y;
	char c;
	int num;
};
node a, b;
queue<node> que;
int xx, yy;

void bfs()
{
	que.push(a);
	visit[a.x][a.y] = false;
	while (!que.empty())		//直到所有的点都遍历过
	{
		node temp = que.front();
		if (temp.x == b.x&&temp.y == b.y)
		{
			printf("To get from %c%d to %c%d takes %d knight moves.\n", a.c, a.y, b.c, b.y, temp.num);
			return;
		}
		que.pop();
		for (int i = 0; i < 8; i++)
		{
			node next;
			xx = temp.x + dx[i];
			yy = temp.y + dy[i];
			if (!visit[xx][yy] || xx < 1 || xx > 8 || yy < 1 || yy > 8)//越界就跳过
				continue;
			next.x = xx;
			next.y = yy;
			next.num = temp.num + 1;
			visit[xx][yy] = false;
			que.push(next);
		}
	}
}
int main()
{
	while (~scanf("%c%d %c%d", &a.c, &a.y, &b.c, &b.y))
	{
		getchar();				//除去换行符
		while (!que.empty())	//每次都要要清空队列
			que.pop();
		a.x = a.c - 'a' + 1;
		b.x = b.c - 'a' + 1;
		a.num = 0;
		memset(visit, true, sizeof(visit));
		bfs();
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值