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}