Article 2 of spiral Matrix

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.