24: Snake-filled array and snake-filled array

Source: Internet
Author: User

24: Snake-filled array and snake-filled array
24: Snake-filled array

  • View
  • Submit
  • Statistics
  • Question
Total time limit:
1000 ms
 
Memory limit:
65536kB
Description

Fill the square matrix with numbers 1, 2, 3, 4,..., n * n, the n2 number, and the scale is n * n.

Snake filling method:

For each left bottom-Right diagonal line, numbers 1, 2 ,..., 2n-1; in the order of numbers from small to large, fill in the numbers from small to large with each diagonal line, where the number is an odd number from bottom to right fill in, number is an even number from top right to bottom left fill in.

For example, when n = 4, the square matrix is filled in the following form:

1  2  6  73  5  8  134  9  12 1410 11 15 16
Input
Enter a positive integer n not greater than 10, indicating the number of rows in the square matrix.
Output
Output the square matrix. Two Adjacent Elements are separated by a single space.
Sample Input
4
Sample output
1 2 6 73 5 8 134 9 12 1410 11 15 16
1 # include <iostream> 2 # include <cstdio> 3 # include <cmath> 4 # include <cstring> 5 using namespace std; 6 int tot = 1; 7 int ans = 2; 8 int now = 1; // 1 down 2 up 9 int a [101] [101]; 10 int main () 11 {12 int n; 13 cin> n; 14 int I = 1, j = 2; 15 cout <1 <""; 16 while (tot! = N * n) 17 {18 if (now = 1) 19 {20 21 a [I] [j] = ans; 22 ans ++; 23 tot ++; 24 if (j = 1 | I = n) 25 {26 if (j = 1 & I! = N) 27 I ++; 28 else j ++; 29 now = 2; 30 continue; 31} 32 else33 {34 I ++; 35 j --; 36} 37 38} 39 if (now = 2) 40 {41 42 a [I] [j] = ans; 43 ans ++; 44 tot ++; 45 if (I = 1 | j = n) 46 {47 if (I = 1 & j! = N) 48 j ++; 49 else I ++; 50 now = 1; 51 continue; 52} 53 else54 {55 I --; 56 j ++; 57} 58} 59 else now = 1; 60} 61 for (int I = 1; I <= n; I ++) 62 {63 for (int j = 1; j <= n; j ++) 64 {65 if (I = 1 & j = 1) continue; 66 else67 cout <a [I] [j] <""; 68} 69 cout <endl; 70} 71 return 0; 72}

 

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.