AcWing 3208. Z-shaped scan

In the image coding algorithm, a given square matrix needs to be Zigzag Scan.
Given an n×n matrix, the zigzag scanning process is shown in the figure below:

zig.png

For the following 4×4 matrix,
1 5 3 9
3 7 5 6
9 4 6 4
7 3 1 3
Z-scan it to get a sequence of length 16: 1 5 3 9 7 3 9 5 4 7 3 6 6 4 1 3.

Please implement a zigzag scanning program, given an n×n matrix, output the result of zigzag scanning on this matrix.

The first line of the input format
contains an integer n, which represents the size of the matrix.

The second line to the n+1th line of the input contains n positive integers, separated by spaces, to represent the given matrix.

The output format
outputs one line, which contains n×n integers, separated by spaces, which represents the result of the input matrix after zigzag scanning.

The data range is
1≤n≤500, and the
matrix elements are positive integers not exceeding 1000.

Input example:
4
1 5 3 9
3 7 5 6
9 4 6 4
7 3 1 3

Output example:
1 5 3 9 7 3 9 5 4 7 3 6 6 4 1 3

code show as below:

#include <iostream>
using namespace std;
const int N = 510;
int a[N][N];
int main()
{
    
    
    int n;
    cin>>n;
    for (int i = 1;i<=n;i++)
        for (int j = 1;j<=n;j++)
            cin>>a[i][j];
            
    for (int i = 2;i<=n*2;i++)
    {
    
    
        if (i%2)
        {
    
    
            for (int j = 1;j<i;j++)
            {
    
    
                if (j>=1 && j<=n &&i-j>=1 &&i-j<=n)
                cout<<a[j][i-j]<<" ";
            }
        }
        else
        {
    
    
            for(int j = i-1;j;j--)
            {
    
    
                if (j>=1 && j<=n && i-j >= 1&& i-j <=n)
                cout<<a[j][i-j]<<" ";
            }
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_51955470/article/details/114055355