#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int n; #define MAX 21 int a[MAX][MAX]; set s; int sum = 0; int sum1 = 0; int sum2 = 0; int row[MAX]; int col[MAX]; void output(){ for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ if (j){ printf(" "); } printf("%d", a[i][j]); } puts(""); } exit(0); } bool ok(int a, int b,int ad){ if (row[a] + ad > sum){ return false; } if (col[b] + ad > sum){ return false; } if (a == b){ if (sum1 + ad > sum){ return false; } } if (a == n - b - 1){ if (sum2 + ad > sum){ return false; } } return true; } void add(int a, int b, int ad){ row[a] += ad; col[b] += ad; if (a == b){ sum1 += ad; } if (a == n - b - 1){ sum2 += ad; } } inline void dfs(int aa, int bb){ //cout << aa << " " << bb << endl; if (s.size() == 1){ if (sum1 + (*s.begin()) == sum&&row[aa] + (*s.begin()) == sum&&col[bb] + (*s.begin()) == sum){ a[aa][bb] = *s.begin(); output(); } return; } if (aa == n - 1){ int v = sum - col[bb]; if (s.count(v)){ if (ok(aa, bb, v) == false){ return; } a[aa][bb] = v; s.erase(v); add(aa, bb, v); dfs(aa, bb+1); add(aa, bb, -v); s.insert(v); } return; } if (bb == n - 1){ int v = sum - row[aa]; if (s.count(v)){ if (ok(aa, bb, v) == false){ return; } a[aa][bb] = v; s.erase(v); add(aa, bb, v); dfs(aa + 1, 0); add(aa, bb, -v); s.insert(v); } return; } set::iterator ite; for (ite = s.begin(); ite != s.end(); ite++){ if (ok(aa, bb, (*ite))){ add(aa, bb,(*ite)); int val = *ite; a[aa][bb] = val; s.erase(ite); dfs(aa, bb + 1); s.insert(val); ite = s.lower_bound(val); add(aa, bb, -val); } else{ break; } } } int main(){ scanf("%d", &n); for (int i = 1; i <= n*n; i++){ s.insert(i); sum += i; } sum /= n; dfs(0, 0); return 0; }