[Problem]
[Solution]
#include <iostream> using namespace std; int direct[4][2] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}}; /** * main */ int main(){ int n, i, j, k = 1; cin >> n; // create array int **array = new int*[n]; for(i = 0; i < n; ++i){ array[i] = new int[n]; for(j = 0; j < n; ++j){ array[i][j] = 0; } } // init i = j = n / 2; array[i][j] = 1; // write data bool completed = false; int d = 0, a = 2, cnt = 0; while(!completed){ cnt++; for(int b = 0; b < k; ++b){ i += direct[d][0]; j += direct[d][1]; // completed if(i < 0 || i == n || j < 0 || j == n){ completed = true; break; } array[i][j] = a++; } // change forward steps if(cnt % 2 == 0){ k++; } // change direction d++; d %= 4; } // output result int sum = 0; for(i = 0; i < n; ++i){ for(j = 0; j < n; ++j){ if(i == j || i+j == n-1){ sum += array[i][j]; } cout << array[i][j] << " "; } cout << endl; } cout << sum << endl; return 0; }