Question number: | 201412-2 |
Question name: | zigzag scan |
time limit: | 2.0s |
Memory limit: | 256.0MB |
Problem Description: |
Problem Description
In the image coding algorithm, a given square matrix needs to be zigzag scan (Zigzag Scan). Given an n×n matrix, the process of zigzag scanning is shown in the following figure:
For the following 4×4 matrix, 1 5 3 9 3 7 5 6 9 4 6 4 7 3 1 3 zigzag scan it Then 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 zigzag scanning on this matrix the result of.
input format
The first row of the input contains an integer n that represents the size of the matrix.
The second to n+1th lines of the input each contain n positive integers, separated by spaces, representing the given matrix.
output format
Output a line containing n×n integers, separated by spaces, representing the result of zigzag scanning of the input matrix.
sample input
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
Evaluate use case size and conventions
1≤n≤500, the matrix elements are positive integers not exceeding 1000.
|
Parse
Extract the scanning direction, and determine the selected number according to the scanning direction.
According to the title, there are four directions for scanning: when encountering the boundary, it is necessary to judge the direction of the direction.
right, down, down left, up right
code
C++
#include <iostream>
#include <vector>
#define MAX_LENGTH 501
using namespace std;
enum Direction{Bottom,Bottom_left,Right,Top_right}flag;
int grad[MAX_LENGTH][MAX_LENGTH];
int main(int argc, char** argv) {
int n;
vector<int> vec_Z;
cin>>n;
//输入
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cin>>grad[i][j];
}
}
//初始化第一个位置
int i=1,j=1;
flag=Right;
vec_Z.push_back(grad[1][1]);
//开始Z扫描
for(int k=1;k<n*n;k++)
{
switch(flag)
{
case Bottom:
i++;
vec_Z.push_back(grad[i][j]);
//如果在左边界,则左上;右边界,则右下
if(j==1)
flag=Top_right;
else if(j==n)
flag=Bottom_left;
break;
case Bottom_left:
i++;j--;
vec_Z.push_back(grad[i][j]);
//到达左边界时,换方向 下
if(j==1&&i!=n)
flag=Bottom;
else if(i==n)
flag=Right;
break;
case Right:
j++;
vec_Z.push_back(grad[i][j]);
if(i==1)//是否在上界
flag=Bottom_left;
else if(i==n)
flag=Top_right;
break;
case Top_right:
i--;j++;
vec_Z.push_back(grad[i][j]);
//到达上界 方向为右边
if(i==1&&j!=n)
flag=Right;
else if(j==n)//到达右界 ,方向向下
flag=Bottom;
break;
}
}
//输出序列
for(vector<int>::iterator it=vec_Z.begin();it!=vec_Z.end();it++)
cout<<*it<<' ';
return 0;
}