http://www.tsinsen.com/A1111
#include "bits/stdc++.h"
using namespace std;
bool Prime[205], Used[205], Can;
int n, Maps[15][15], sup;
void Dfs(int Solved, int r, int c) {
if (Solved >= sup) {
Can = true;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (j > 0) putchar(' ');
printf("%d",Maps[i][j]);
}
putchar('\n');
}
return;
}
for (int i = 2; i <= sup; ++i) if (!Used[i] && !Can) {
if (r > 0 && !Prime[Maps[r - 1][c] + i]) continue;
if (c > 0 && !Prime[Maps[r][c - 1] + i]) continue;
Used[i] = true; Maps[r][c] = i;
if (c + 1 >= n) Dfs(Solved + 1, r + 1, 0);
else Dfs(Solved + 1, r, c + 1);
Used[i] = false;
}
}
int main() {
for (int i = 2; i < 205; ++i)
Prime[i] = true;
for (int i = 2; i < 205; ++i) if (Prime[i])
for (int k = i + i; k < 205; k += i)
Prime[k] = false;
Used[1] = Maps[0][0] = 1;
scanf("%d", &n); sup = n * n;
Dfs(1, 0, 1);
if (!Can) puts("NO");
return 0;
}