C language daily practice (2)-snake Array

Source: Internet
Author: User

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:



Related Article

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.