hdoj 1372 Knight Moves

20 篇文章 0 订阅

题目大意:国际象棋骑士从起点到终点的最少步数

解题思路:水题.....宽度遍历

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <climits>
#include <algorithm>
using namespace std;

struct node
{
	int x, y, step;
};

const int maxn = 8;
bool square[maxn][maxn];
int sx, sy, ex, ey;
int dir[8][2] = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}};

int bfs();

int main()
{
	char str1[5], str2[5];
	while(scanf("%s %s", str1, str2) != EOF)
	{
		sx = str1[1] - '1'; sy = str1[0] - 'a';
		ex = str2[1] - '1'; ey = str2[0] - 'a';
		memset(square, 0, sizeof(square));
		int ans = bfs();
		printf("To get from %s to %s takes %d knight moves.\n", str1, str2, ans);
	}
	
	return 0;
}

int bfs()
{
	queue<node> que;
	node tmp, t;
	t.x = sx;
	t.y = sy;
	t.step = 0;
	square[t.x][t.y] = true;
	que.push(t);
	while(!que.empty())
	{
		tmp = que.front();
		if(tmp.x == ex && tmp.y == ey)
			return tmp.step;
		que.pop();
		for(int i = 0; i < 8; i++)
		{
			t.x = tmp.x + dir[i][0];
			t.y = tmp.y + dir[i][1];
			t.step = tmp.step + 1;
			if(t.x >= 0 && t.x < 8 && t.y >= 0 && t.y < 8 && !square[t.x][t.y])
			{
				square[t.x][t.y] = true;
				que.push(t);
			}
		}
	}
	return -1;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值