I wrote about the spiral MatrixAlgorithm
However, the clockwise algorithm is implemented.
This upload method is a counter-clockwise method, in fact, just exchange the rows and columns.
The specific method, the train of thought is the same with clockwise, the train of thought See http://blog.csdn.net/xuchao1229/article/details/8117312
Below isCodeAnd running results
# Include <stdio. h> # define Max 20int main (void) {int A [Max] [Max]; int N; // matrix base int I, j, k; int base = 1; printf ("Enter the matrix base: \ n"); scanf ("% d", & N); For (k = 0; k <n/2; k ++) {for (I = K; I <= n-1-k; I ++) A [I] [k] = base ++; For (j = k + 1; j <n-1-k; j ++) A [n-1-k] [J] = base ++; for (I = n-1-k; I> K; I --) A [I] [n-1-k] = base ++; For (j = n-1-k; j> K; j --) A [k] [J] = base ++; if (N % 2 = 1) A [(n-1)/2] [(n-1)/2] = base; // determine the number of the Center} printf ("Spiral matrix output: \ n"); for (I = 0; I <n; I ++) {for (j = 0; j <n; j ++) printf ("%-4D", a [I] [J]); printf ("\ n");} return 0 ;}
By the way, when the base number is an odd number, the central point number appears separately, not a rectangle, therefore, before assigning values, we need to make a judgment, that is
If (N % 2 = 1) A [(n-1)/2] [(n-1)/2] = base; // determine the number of the center
However, the subsequent base cannot be added with the auto-incrementing symbol. If it is added because it is an odd number, each round of loop will be judged. If it has the auto-incrementing symbol, the next round of rectangle assignment will be 2 different from the previous number, and the result is incorrect, so the Base will be OK, and the previous number will be passed to the subsequent number.
Run