UVa 439 & SDU 1372 - Knight Moves

19 篇文章 0 订阅
12 篇文章 0 订阅

传送门UVa 439 & SDU 1372 - Knight Moves

题意:国际象棋中的骑士跳,给一个起点和终点,求最小步数。


刚开始看不懂怎么跳。。我捉急的知识面。。。。

百度了一下,骑士跳就是中国象棋中马的跳法。


参考了shuangde800的解题报告,很好的思路。

引用一下他的说明

分析:

这题也是一道十分经典的搜索入门题。  由于题目是指定象棋中马的开始位置,与目标位置, 要求马以最少的步数走到目标位置。 凡是求最短步数的,一般用BFS做比较好。

求步数时, 有个小技巧, 开个vis数组,初始化为0, 然后这个用来记录走的步数,而不仅仅是用来标记是否走过。具体见代码


刚才被上一道题搞得欲仙欲死,到最后也没搞出来,现在脑子还是混乱的。哎。。。。


#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;

struct node
{
	int x, y;
};

char start[3], target[3];
queue<node> qu;
int vis[10][10];
int dir[8][2] = {{-2, -1}, {-2, 1}, {2, -1}, {2, 1}, {-1, 2}, {-1, -2}, {1, 2}, {1, -2}};
void BFS();

int main()
{
	//freopen("input.txt", "r", stdin);
	while (~scanf("%s %s%*c", start, target))
	{
		memset(vis, 0, sizeof(vis));
		BFS();
	}
	return 0;
}

void BFS()
{
	node now;
	now.x = start[0] - 'a';
	now.y = start[1] - '1';
	qu.push(now);
	vis[now.x][now.y] = 1;
	while (!qu.empty())
	{
		if (qu.front().x == target[0] - 'a' && qu.front().y == target[1] - '1')
		{
			printf("To get from %s to %s takes %d knight moves.\n", start, target, vis[qu.front().x][qu.front().y] - 1);
			while (!qu.empty())
				qu.pop();
			return;
		}
		for (int i = 0; i < 8; i++)
		{
			int dx = qu.front().x + dir[i][0];
			int dy = qu.front().y + dir[i][1];
			if (dx >= 0 && dx < 8 && dy >= 0 && dy < 8 && !vis[dx][dy])
			{
				vis[dx][dy] = vis[qu.front().x][qu.front().y] + 1;
				node temp;
				temp.x = dx, temp.y = dy;
				qu.push(temp);
			}
		}
		qu.pop();
	}
}

			


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值