#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
bool been[8][8];
int dir[8][2];
int route[64];
int ct;
bool found;
struct pointInfo{
int x;
int y;
int validUnvisitedNextNum;
pointInfo(int nx, int ny) {
x = nx;
y = ny;
validUnvisitedNextNum = 0;
}
};
void initial() {
dir[0][0] = -2, dir[0][1] = -1;
dir[1][0] = -2, dir[1][1] = 1;
dir[2][0] = 2, dir[2][1] = -1;
dir[3][0] = 2, dir[3][1] = 1;
dir[4][0] = -1, dir[4][1] = -2;
dir[5][0] = -1, dir[5][1] = 2;
dir[6][0] = 1, dir[6][1] = -2;
dir[7][0] = 1, dir[7][1] = 2;
memset(been, false, sizeof(been));
memset(route, 0, sizeof(route));
ct = 0;
found = false;
}
int point(const int x, const int y) {
return x * 8 + y + 1;
}
bool valid(const int x, const int y) {
return (x >= 0 && x <= 7 && y >= 0 && y <= 7);
}
bool compare(const pointInfo& a, const pointInfo& b) {
return a.validUnvisitedNextNum < b.validUnvisitedNextNum;
}
void dfs(int x, int y) {
if(ct == 64) {
found = true;
return;
}
vector<pointInfo> next;
for(int i = 0; i < 8; i++) {
int newx = x + dir[i][0];
int newy = y + dir[i][1];
if(valid(newx, newy) && !been[newx][newy]) {
pointInfo tmp(newx, newy);
for(int j = 0; j < 8; j++) {
int tmpnewx = newx + dir[j][0];
int tmpnewy = newy + dir[j][1];
if(valid(tmpnewx, tmpnewy) && !been[tmpnewx][tmpnewy]) {
tmp.validUnvisitedNextNum++;
}
}
next.push_back(tmp);
}
}
if(next.size() == 0) return;
sort(next.begin(), next.end(), compare);
for(int i = 0; i < next.size(); i++) {
int newx = next[i].x;
int newy = next[i].y;
route[ct++] = point(newx, newy);
been[newx][newy] = true;
dfs(newx, newy);
if(found) {
break;
}
been[newx][newy] = false;
ct--;
}
}
void print() {
cout << route[0];
for(int i = 1; i <= 63; i++) {
cout << ' ' << route[i];
}
cout << endl;
}
int main() {
int n;
while(cin >> n && n != -1) {
initial();
route[ct++] = n;
int st_x = (n - 1) / 8, st_y = (n - 1) % 8;
been[st_x][st_y] = true;
dfs(st_x, st_y);
print();
}
return 0;
}
1153. 马的周游问题
最新推荐文章于 2024-04-19 10:57:44 发布