uva439 Knight Moves (搜索 BFS, BFS启蒙题)

题意:HDU1372

思路:HDU1372

算法复杂度: 棋盘是固定的8*8 所有复杂度是常复杂度o(1)。 (不知道这样算对不对, 刚学。 还望大牛指点)

代码:


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

#define MAX_R 8 
#define DIR_NUM 8
#define MAX_QUE 2000
const int dir[DIR_NUM][2] = {{1,2}, {-1,2}, {1,-2}, {-1,-2}, {2,1}, {-2,1}, {2,-1}, {-2,-1}};

struct point
{
	int x;
	int y;
	int times;
};

point star, end;
bool vis[MAX_R + 3][MAX_R + 3];

int BFS();

int main()
{
	char x1, x2;
	int y1, y2;
	while (scanf("%c%d %c%d%*c", &x1, &y1, &x2, &y2) == 4) {
		// init
		memset(vis, 0, sizeof(vis));
		star.x = x1 - 96;		// 'a' - 1 = 96	
		star.y = y1;
		star.times = 0;
		end.x = x2 - 96;
		end.y = y2;
		end.times = 0;
		
		// output
		printf("To get from %c%d to %c%d takes %d knight moves.\n", x1, y1, x2, y2, BFS());
	}

	return 0;
}

int BFS()
{
	if (star.x == end.x && star.y == end.y) {
		return 0;
	}

	point *que[MAX_QUE];
	int head = 0;
    int	tail = 0;
	que[tail++] = ☆

	while (head < tail) {
		point *root = que[head++];

		if (root->x == end.x && root->y == end.y) {
			return root->times;
		}

		for (int i = 0; i < DIR_NUM; i++) {
			point *child = new point;
			child->x = root->x + dir[i][0];
			child->y = root->y + dir[i][1];
			child->times = root->times;

			if (child->x >= 1 && child->x <= MAX_R
			 && child->y >= 1 && child->y <= MAX_R
			 && vis[child->x][child->y] == 0) {
				vis[child->x][child->y] = 1;
				child->times++;
				que[tail++] = child;
			}
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值