AcWing one question every day during winter vacation-Day36Z font 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:

Insert picture description here

For the following 4×4 matrix,

1 5 3 9
3 7 5 6
9 4 6 4
7 3 1 3
After zigzag scanning, a sequence of length 16 is obtained: 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.

Input format
The first line of input 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.

Output format
Output one line, containing n×n integers, separated by spaces, representing the result of the input matrix after zigzag scanning.

Data range
1 ≤ n ≤ 500, 1≤n≤500,1n5 0 0 , the
matrix elements are positive integers not exceeding 1000.

Input sample:

4
1 5 3 9
3 7 5 6
9 4 6 4
7 3 1 3

Sample output:

1 5 3 9 7 3 9 5 4 7 3 6 6 4 1 3

Analysis: Determine whether the previous one crosses the boundary each time you walk, and change the direction if it crosses the boundary

Code:

#include<bits/stdc++.h>
using namespace std;
const int N=505;//z:0下 1上 h:0下 1右
int n,a[N][N],zx[]={
    
    1,-1},zy[]={
    
    -1,1},hx[]={
    
    1,0},hy[]={
    
    0,1};
int main(){
    
    
    cin>>n;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            cin>>a[i][j];
    int i=1,j=2,flagh=1,flagz=0;
    cout<<a[1][1]<<" ";
    if(n==1) j=1;
    else cout<<a[i][j]<<" ";
    while(i!=n||j!=n){
    
    
        int x=i+zx[flagz],y=j+zy[flagz];
        if(a[x][y]) i+=zx[flagz],j+=zy[flagz];
        else{
    
    
            if(y<1&&x<=n&&x>=1) flagz=1,flagh=0;
            else if(x<1&&y>=1&&y<=n) flagz=0,flagh=1;
            else if(x<=n&&x>=1&&y>n||y>n&&x<1) flagz=0,flagh=0;
            else if(x>n&&y>=1&&y<=n||y<1&&x>n) flagz=1,flagh=1;
            i+=hx[flagh],j+=hy[flagh];
        }
        cout<<a[i][j]<<" ";
    }
}

Guess you like

Origin blog.csdn.net/messywind/article/details/113832280