A detailed explanation of Z-arrangement (C + +)

A detailed explanation of the problem of zigzag arrangement (C + +): Problem Description: given a matrix matrix, output the content of matrix after Z-...
A detailed explanation of the problem of zigzag arrangement (C + +):

A detailed explanation of the problem of zigzag arrangement (C + +):

Problem Description: given a matrix matrix, output the content of matrix after Z-arrangement.

Original matrix:


Output form:

Algorithm analysis and detailed answer:

To solve such a problem, we may not be able to start at first, but as long as we carefully observe the trend process of Z-matrix, it is not difficult to find the law. For any element in the original matrix matrix, the law of traversal direction of matrix[i][j] can be divided into the following three cases:

1. If the ordinate j in matrix[i][j] is even, and i==0 or i==SIZE-1, then the direction of traversal path in matrix is to move one grid to the right.

2. If the abscissa I in matrix[i][j] is odd, and j==0 or j==SIZE-1, the direction of traversal path in matrix is to move down one grid.

3. In addition to the above rules, if the sum of the abscissa and ordinate of the matrix element matrix[i][j] i+j is even, then the direction of the traversal path in the matrix is to the right

If i+j is an odd number, then the direction of the traversal path in the matrix is to move one lattice to the lower left corner.

c++ Code:

#include<iostream> #include<iomanip> using namespace std; const int SIZE = 8; int main() { int matrix[SIZE][SIZE]= { 0 }; int a[SIZE][SIZE] = { 0 }; int* ptr = &(matrix[0][0]); for (int i = 0; i < SIZE*SIZE; i++) *ptr++ = i; cout << "The original matrix is as follows:" << endl; for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) cout << setw(4) << *(*(matrix + i) + j); cout << endl; } //Conduct Z-Glyph arrangement int i = 0, j = 0; for (int x = 0; x < SIZE; x++) { for (int y = 0; y < SIZE; y++) { *(*(a + i) + j) = *(*(matrix + x) + y); if ((i == 0 || i == SIZE - 1) && j % 2 == 0) { j++; continue; } if ((j == 0 || j == SIZE - 1) && i % 2 == 1) { i++; continue; } if ((i + j) % 2 == 0) { i--; j++; } else if ((i + j) % 2 == 1) { i++; j--; } } } cout << "The arrangement matrix is as follows:" << endl; for (int k = 0; k < SIZE; k++) { for (int h= 0; h < SIZE; h++) cout << setw(4) << *(*(a + k) + h); cout << endl; } system("pause"); return 0; }

Welcome to comment!

2 December 2019, 15:40 | Views: 5503

Add new comment

For adding a comment, please log in
or create account

0 comments