// 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;
}
Sicily 1153. 马的周游问题
最新推荐文章于 2018-03-21 11:39:24 发布
