#include <stdio.h>
#include <memory.h>
int table[] =
{
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,
79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163,
167, 173, 179, 181, 191, 193, 197, 199
};
char isPrime[] =
{
0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0,
0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1,
0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0,
1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0,
0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1
};
int find(int N, int* pos, int curr_pos)
{
int a, b, i, j, temp;
int curr_value = 1, start;
int stack[100], sp = 1;
stack[0] = 0;
start = 0;
while(1){
a = curr_pos / N; b = curr_pos % N;
for(i = start; i < 46; i++){
if(b == 0){
if(a == 0) temp = curr_value;
else temp = table[i] - pos[(a-1)*N];
}else if(a == 0){
temp = table[i] - pos[curr_pos-1];
}else{
temp = table[i] - pos[(a-1)*N+b];
if(temp + pos[curr_pos-1] > 200 ||
!isPrime[temp + pos[curr_pos-1]]) continue;
}
if(temp < 1) continue;
if(temp > N*N) break;
for(j = 0; j < curr_pos; j++)
if(temp == pos[j]) break;
if(j == curr_pos) break;
}
if(i != 46 && temp <= N*N){
pos[curr_pos++] = temp;
if(curr_pos == N*N) return 1;
stack[sp++] = i;
start = 0;
}else{
curr_pos--;
if(curr_pos < 0) return 0;
sp--;
start = stack[sp]+1;
}
}
}
int main(int argc, char* argv[])
{
int pos[10 * 10];
int N, count, i, j, k;
scanf("%d", &count);
for(k = 0; k < count; k++){
scanf("%d", &N);
if(find(N, pos, 0)){
for(i = 0; i < N; i++){
for(j = 0; j < N; j++){
if(j == 0) printf("%d", pos[i*N+j]);
else printf(" %d", pos[i*N+j]);
}
putchar('/n');
}
}else puts("NO");
}
return 0;
}
Memory: 36K
Time: 2878ms