bool between(int x, int low, int high) {
return low <= x && x <= high;
}
// we use this constant array to help tweaking the (row,col) coordinate
const int D[4][2] = {
{0, 1}, // 0 - right
{1, 0}, // 1 - down
{0, -1}, // 2 - left
{-1, 0} // 3 - up
};
int a[n][n]; // suppose the array is n times n in size
int row = 0, col = 0, dir = 0; // initial direction is "0 - right"
for (int m = n*n; m >= 1; m--) {
a[row][col] = m;
int old_row = row, old_col = col; // remember current coordinate
row += D[dir][0];
col += D[dir][1];
if (!(between(row,0,n-1) && between(col,0,n-1))) { // have to move back
// move back
row = old_row;
col = old_col;
// change direction
dir++;
dir %= 4;
// move again
row += D[dir][0];
col += D[dir][1];
}
}