- Use variables x and y for your position, easier to track that way.
- Use a state variable to track your direction. Counter-clockwise is left, up, right, then down.
- Add a word from each position.
- Advance your position until you hit an edge, then change direction. Do this four times (once for each direction), then increment an edge counter, representing the width of your spiral.
- When you've done this 400 times (20*20), you are done.
The code flows directly from that algorithm. (Note, I haven't compiled this, so you'll have to check for errors yourself).
int x = n - 1; // Start at right.
int y = n - 1; // Start at bottom.
int spiral = 0; // Track the edges already visited (spiral).
int direction = 0; // 0=left, 1=up, 2=right, 3=down. You could also use an enum.
string s; // String builder.
for (int count = 0; count < 400; count++) { // One word per cell, 400 cells.
s = s + a[x][y] + " "; // Add the word.
if (direction == 0) { // Left
if (x > spiral) x--; // Check edge, advance if no edge.
else { y--; direction = 1; } // Change direction to up if edge is hit.
} else if (direction == 1) { // Up
if (y > spiral) y--; // Check edge, advance if no edge.
else { x++; direction = 2; } // Change direction to right if edge is hit.
} else if (direction == 2) { // Right
if (x < (n - 1) - spiral) x++; // Check edge, advance if no edge.
else { y++; direction = 3; spiral++; } // Change edge and direction to down.
} else if (direction == 3) { // Down
if (y < (n - 1) - spiral) y++; // Check edge, advance if no edge.
else { x--; direction = 0; } // Change direction to left if hit.
}
}