UVa439 Knight Move 骑士的移动(bfs)

题目大意:有一个8*8的国际象棋棋盘,输入起点和终点,问马最少走几步。

方法:用一次bfs,难点应该是计算最少步数,解决方法是设置一个层,每次遍历父节点周围的子节点就执行子节点的层=父节点的层+1,这样一来每个节点都有自己的层,每个节点都是公平的所以最后搜索出来直接就是最小步数。

代码:

#include<iostream>
#include <string>
#include <string.h>
#include <queue>
using namespace std;
int direct[16] = { 2,1,1,2,-2,1,-1,2,-2,-1,-1,-2,2,-1,1,-2 };
int mp[10][10]; int vis[10][10]; int lay[10][10];
struct Node {
	int x, y;
	Node(){}
	Node(int _x,int _y):x(_x),y(_y){}
	bool operator==(const Node &u) {
		return x== u.x&& y == u.y;
	}
};
void bfs(int x, int y, int count) {
	queue<Node>q;
	queue<Node>endqueue;
	q.push(Node(x, y)); Node t;
	endqueue.push(q.back());
	while (!q.empty()) {
		 t = q.front(); q.pop(); 
		vis[t.x][t.y] = 1;
		if (mp[t.x][t.y] == 1) {
			printf("To get from %c%d to %c%d takes %d knight moves.\n", x + 'a' - 1, y, t.x + 'a' - 1,t.y,lay[t.x][t.y]);
			break;
		}
		for (int i = 0; i < 16; i += 2) {
			int x0 = t.x + direct[i];
			int y0 = t.y + direct[i + 1];
			if (!vis[x0][y0] && x0 >= 1 && x0 <= 8 && y0 >= 1 && y0 <= 8) {
				lay[x0][y0] = lay[t.x][t.y] + 1; q.push(Node(x0, y0));
			}
		}
	}
}int main()
{
string s1,e1;
while (cin >> s1 && cin >> e1) {
	memset(mp, 0, sizeof(mp));
	memset(vis, 0, sizeof(vis));
	memset(lay, 0, sizeof(lay));
	mp[e1[0] - 'a' + 1][e1[1] - '0'] = 1;
	bfs(s1[0] - 'a' + 1, s1[1] - '0',0);
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值