首先将图形中每个点的位置关系梳理出来,假设每个点可以向6个方向进行移动,可以移动到的位置就记录成对应的数字,不能移动到的位置就记录成-1。记录结束之后,就利用移位操作记录状态,每个数字都占据一位,以1表示该数字是存在的,以0表示是不存在的,然后从初始状态开始bfs,放入队列,每次都从队列中取出队头,作为当前的状态,然后分析每个数字是否存在,如果数字在当前的状态是存在的,就开始判断每个数字是否能够向各个方向移动,移动包含两个点,第一点,数字在当前的方向必须是能够移动的,第二点 ,数字移动的方向上必须存在空位;如果数字能够移动,那么就计算出数字移动之后的状态,如果该状态在之前没有遍历到(也就是之前没有处理过),那么就将当前的状态放入队列,同时要记录移动的状态信息也就是从哪个数字移动到了哪个点,然后要记录长度信息以及更改状态的访问信息,最后递归打印结果即可,具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;
const int maxn = 1 << 15 + 10;
int num;
bool visit[maxn];
int pre[maxn], path[maxn][2],length[maxn];
int state,fin_s,ed_p;
int q[maxn],init;
int pos[15][6]{
{-1,-1,-1,-1,1,2},
{-1,0,-1,2,3,4},
{0,-1,1,-1,4,5},
{-1,1,-1,4,6,7},
{1,2,3,5,7,8},
{2,-1,4,-1,8,9},
{-1,3,-1,7,10,11},
{3,4,6,8,11,12},
{4,5,7,9,12,13},
{5,-1,8,-1,13,14},
{-1,6,-1,11,-1,-1},
{6,7,10,12,-1,-1},
{7,8,11,13,-1,-1},
{8,9,12,14,-1,-1},
{9,-1,13,-1,-1,-1}
};
bool Move(int i,int j){
if (pos[i][j] < 0 || !(state&(1 << pos[i][j]))) return false;
while (pos[i][j] >= 0){
if (!(state&(1 << pos[i][j]))){
ed_p = pos[i][j];
return true;
}
i = pos[i][j];
}
return false;
}
void bfs(){
int front = 0, rear = 1;
q[front] = state;
length[state] = 0;
visit[state] = true;
while (front < rear){
state = q[front];
if (state == fin_s){
return;
}
for (int i = 0; i < 15; i++){
if ((1 << i)&state){
for (int j = 0; j < 6; j++){
if (Move(i, j)){
int temp_s = state;
int from = i;
int from_t = from;
while (from_t != ed_p){
temp_s ^= (1 << from_t);
from_t = pos[from_t][j];
}
temp_s ^= (1 << ed_p);
if (!visit[temp_s]){
visit[temp_s] = true;
q[rear] = temp_s;
pre[temp_s] = state;
path[temp_s][0] = from + 1;
path[temp_s][1] = ed_p + 1;
length[temp_s] = length[state] + 1;
rear++;
}
}
}
}
}
front++;
}
}
void Print(int cur){
if (length[cur] != 0) Print(pre[cur]);
if (cur!=init) cout << path[cur][0] << " " << path[cur][1];
if (cur != fin_s&&cur!=init) cout << " ";
}
int main(){//注意下标从0开始
int T;
cin >> T;
int start_s = (1<<15)-1;
while (T--){
memset(visit, 0, sizeof(visit));
cin >> num;
num--;
fin_s = 1 << num;
state = start_s;
state ^= fin_s;
init = state;
bfs();
cout << length[fin_s] << endl;
Print(fin_s);
cout << endl;
}
return 0;
}