For example, enter 1, 2, 3,..., n * n in the n * n square matrix and fill it with a snake. For example, if n = 4, the square matrix is:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
In the square matrix above, the extra space knowledge does not need to be output strictly to facilitate observation of the matrix, n <= 8.
Solution: we need to think a little bit about this: in the process of filling the matrix by a snake, we noticed this fixed process: bottom, left, top, right, bottom, left, top, right ...... this process is cyclical, that is to say, we have found the law to Solve the Problem ~ Next we just need to simulate this process!
Code:
# Include
# Include
Int a [10] [10]; int main () {int I, j, n, count; memset (a, 0, sizeof ()); scanf ("% d", & n); count = a [I = 1] [j = n] = 1; // assign an initial value in the direction: right-> left while (count <n * n) {while (I
1 &&! A [I] [J-1]) a [I] [-- j] = + + count; // left while (I> 1 &&! A [I-1] [j]) a [-- I] [j] = ++ count; // while (j)
When filling in each direction, determine whether the next position is appropriate (out-of-bounds or filled )~
Running result: