全排列之后筛选。。
#include "string"
#include "iostream"
#include "cstdio"
#include "cmath"
#include "set"
#include "queue"
#include "vector"
#include "cctype"
#include "sstream"
#include "cstdlib"
#include "cstring"
#include "stack"
#include "ctime"
#include "algorithm"
#define pa pair<int,int>
#define Pi M_PI
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3fLL
using namespace std;
typedef long long LL;
const int M=500005;
int n,x;
int ans[11],res[M][11],a[11],vis[11];
bool ok(int m)
{
int flag[11];
for(int i = 0 ; i <= 10; i++)
flag[i] = 0;
for(int i = 1; i <= n ; i++)
{
flag[res[m][i]] = 1;
if((res[m][i] == 1 && res[m][i+1] == 9 && flag[5] == 0)|| (res[m][i] == 9 && res[m][i+1] == 1 && flag[5] == 0) ||
(res[m][i] == 1 && res[m][i+1] == 3 && flag[2] == 0)|| (res[m][i] == 3 && res[m][i+1] == 1 && flag[2] == 0) ||
(res[m][i] == 1 && res[m][i+1] == 7 && flag[4] == 0)|| (res[m][i] == 7 && res[m][i+1] == 1 && flag[4] == 0) ||
(res[m][i] == 2 && res[m][i+1] == 8 && flag[5] == 0)|| (res[m][i] == 8 && res[m][i+1] == 2 && flag[5] == 0) ||
(res[m][i] == 4 && res[m][i+1] == 6 && flag[5] == 0)|| (res[m][i] == 6 && res[m][i+1] == 4 && flag[5] == 0) ||
(res[m][i] == 3 && res[m][i+1] == 9 && flag[6] == 0)|| (res[m][i] == 9 && res[m][i+1] == 3 && flag[6] == 0) ||
(res[m][i] == 7 && res[m][i+1] == 9 && flag[8] == 0)|| (res[m][i] == 9 && res[m][i+1] == 7 && flag[8] == 0) ||
(res[m][i] == 3 && res[m][i+1] == 7 && flag[5] == 0)|| (res[m][i] == 7 && res[m][i+1] == 3 && flag[5] == 0) )
return 0;
}
return 1;
}
void DFS(int cnt)//全排列
{
if(cnt == n + 1)
{
x++;
for(int i = 1; i <= n ; i++)
res[x][i] = ans[i];
return ;
}
for(int i = 1; i <= n; i++)
{
if(!vis[a[i]])
{
ans[cnt] = a[i];
vis[a[i]] = 1;
DFS(cnt+1);
vis[a[i]] = 0;
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
memset(res, -1, sizeof(res));
scanf("%d",&n);
for(int i = 1; i <= n ; i++)
scanf("%d",&a[i]);
sort(a+1,a+n+1);
x = 0;
memset(vis, false, sizeof(vis));
DFS(1);
int temp = x;
for(int i = 1; i <= temp; i++)
{
if(ok(i) == 0)
x--;
}
printf("%d\n",x);
for(int i = 1; i <= temp ; i++)
{
if(ok(i))
{
for(int j = 1; j < n ; j++)
printf("%d ",res[i][j]);
printf("%d\n",res[i][n]);
}
}
}
return 0;
}