3208. Zigzag Scan
In the image coding algorithm, a given square matrix needs to be ZZZ zigzag scanning (Zigzag Scan).
Given a n × nn × nn×matrix of n ,ZZThe zigzag scanning process is shown in the figure below:
For the following4×4 4×44×Matrix of 4 ,
1 5 3 9
3 7 5 6
9 4 6 4
7 3 1 3
Its ZZThe length of the zigzag scan is16 16. 1 . 6 sequences:1 5 3 9 7 3 9 5 4 7 3 6 6 4 1 3。
Please implement a ZZZ zigzag scanning procedure, a givenn × nn × nn×n matrix, outputZZfor this matrixZ result zigzag scan.
Input format
The first line of input contains an integer nnn represents the size of the matrix.
Input the second line to the n + 1 n+1n+1 line each line containsnnn positive integers, separated by spaces, represent a given matrix.
Output format
Output one line, including n × nn×nn×n integers, separated by spaces, indicating that the input matrix passes throughZZZ -shape results after scanning.
Data range
1 ≤ n ≤ 500, 1≤n≤500,1≤n≤5 0 0 , the
matrix elements are not more than1000 10001 0 0 0 is a positive integer.
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
Ideas:
As we all know, a two-dimensional matrix has a total of 2 n − 1 2n-12 n−1 positive diagonal and2 n − 1 2n-12 n−1 sub-diagonal line.
And here we find that the scans are all along the sub-diagonal line. The picture below is to scan a5 × 5 5 × 55×5 Illustration of the matrix:
We found that the scan can be divided into two directions,右上
and左下
.
And because n × nn×nn×n matrix, all diagonal sub45
degrees, i.e. the slope is1
, we havey = x + b;
i.e.x - y = b;
whereb
is the intercept, is fixed, i.e., the difference between the coordinates of the sub-diagonals is fixed.
Therefore, this relationship can be used to calculate coordinates.
Further, when we give the above figure 2n - 1
diagonals from 0 ~ 2n - 2
time number, you will find that the even-numbered diagonal down the right, and diagonal left is an odd-numbered laid down, as shown below:
Of course, when we scan, we should also ensure that the subscript does not cross the boundary.
Java code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] arr = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = sc.nextInt();
}
}
//注意这里i表示的是当前遍历的是第几条副对角线,而非横坐标,共2n - 1条副对角线
for (int i = 0; i <= 2 * n - 1; i++) {
if ((i & 1) == 0) {
//第偶数条对角线往右上走
for(int j = i; j >= 0;j--){
//j表示当前副对角线起点的横坐标,纵坐标由i - j算出即可
if (j >= 0 && j < n && i - j >= 0 && i - j < n) {
//坐标越界检查
System.out.print(arr[j][i - j] + " ");
}
}
}else{
//第奇数条对角线往左下走
for (int j = 0; j <= i; j++) {
//j表示当前副对角线起点的横坐标,纵坐标由i - j算出即可
if (j >= 0 && j < n && i - j >= 0 && i - j < n) {
//坐标越界检查
System.out.print(arr[j][i - j] + " ");
}
}
}
}
}
}