Knight Moves BFS

又一次做到这一题了, 记得第一次做的时候大笑, 理解成DFS。(其实当时没有DFS || BFS的概念), 这一次做这题信手捏来。

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

#define DIRECTION_N 8
#define MAP_SIZE 8
#define REACHED 1
#define UNREACHED 0

struct Node {
	int x, y;
	int steps;
};

const int direction[DIRECTION_N][2] = {{1,2}, {-1,2}, {1,-2}, {-1,-2}, {2,1}, {-2,1}, {2,-1}, {-2,-1}};
int map[MAP_SIZE][MAP_SIZE];
Node end;

int BFS(Node);
bool ok(Node);

int main()
{
	Node star;

	char x1, x2, y1, y2;
	while (scanf("%c%c %c%c%*c", &x1, &y1, &x2, &y2) != EOF) {
		memset(map, UNREACHED, sizeof(map));		//全地图标记未到达

		star.x = (int)(x1 - 'a');	
		star.y = (int)(y1 - '1');
		star.steps = 0;
		end.x = (int)(x2 - 'a');
		end.y = (int)(y2 - '1');

		printf("To get from %c%c to %c%c takes %d knight moves.\n", x1, y1, x2, y2, BFS(star));
	}

	return 0;
}

//广搜索
int BFS(Node star)
{
	queue<Node> que;	
	que.push(star);

	while (!que.empty()) {
		Node root = que.front();
		que.pop();

		if (root.x == end.x && root.y == end.y) {		//出口
			return root.steps;
		}

		for (int i = 0; i < DIRECTION_N; i++) {
			Node child = root;

			child.x += direction[i][0];
			child.y += direction[i][1];
			child.steps++;

			if (ok(child)) {
				map[child.x][child.y] = REACHED;
				que.push(child);
			}
		}
	}

	printf("no way\n");
	return 0;
}

//判断行走是否合法
bool ok(Node now)
{
	if (now.x >= 0 && now.x < MAP_SIZE && now.y >= 0 && now.y < MAP_SIZE && map[now.x][now.y] == UNREACHED) {
		return true;
	}

	return false;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值