Sicily 1153. 马的周游问题

// DFS,须剪枝
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int k, res[64];
bool visit[64];
int direct[][2] = { { -2, 1 }, { -1, 2 }, { 1, 2 }, { 2, 1 }, { 2, -1 },
		{ 1, -2 }, { -1, -2 }, { -2, -1 } };
struct Grid {
	int num;
	int way;
} g[8];

bool cmp(Grid a, Grid b) {
	return a.way < b.way;
}

void count(int now) {
	int x = now / 8;
	int y = now % 8;

	for (int i = 0; i < 8; i++) {
		int nx = x + direct[i][0];
		int ny = y + direct[i][1];
		int next = nx * 8 + ny;

		if (0 <= nx && nx < 8 && 0 <= ny && ny < 8 && !visit[next]) {
			g[k].way = 0;    // 可扩展数
			g[k].num = i;    // 方向
			for (int j = 0; j < 8; j++) {
				int nxx = nx + direct[j][0];
				int nyy = ny + direct[j][1];
				int nextt = nxx * 8 + nyy;

				if (0 <= nxx && nxx < 8 && 0 <= nyy && nyy < 8 && !visit[nextt])
					g[k].way++;
			}
			k++;
		}
	}
}

bool dfs(int now, int cnt) {
	if (cnt == 64)
		return true;

	// 对当前格子的可扩展格子的可扩展数进行排序
	k = 0;
	count(now);
	sort(g, g + k, cmp);

	int x = now / 8;
	int y = now % 8;

	// 先走可扩展数较小的格子
	for (int i = 0; i < k; i++) {
		int nx = x + direct[g[i].num][0];
		int ny = y + direct[g[i].num][1];
		int next = nx * 8 + ny;

		// 注意逻辑
		if (0 <= nx && nx < 8 && 0 <= ny && ny < 8 && !visit[next]) {
			visit[next] = true;
			res[cnt] = next;
			if (dfs(next, cnt + 1))
				return true;
			visit[next] = false;
		}
	}
	return false;
}

int main(int argc, char **argv) {
	int src;
	while (cin >> src && src != -1) {
		memset(visit, false, sizeof(visit));

		res[0] = src;
		visit[src - 1] = true;
		dfs(src - 1, 1);

		cout << res[0];
		for (int i = 1; i < 64; i++)
			cout << " " << res[i] + 1;
		cout << endl;
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值