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. Given an n×n matrix, the zigzag scanning process is shown in the following figure: Input format The first line of input contains an integer n, which represents the size of the matrix. Output format Output one line, containing n×n integers, separated by spaces, representing the result of the input matrix after zigzag scanning. Sample input 4 Sample output 1 5 3 9 7 3 9 5 4 7 3 6 6 4 1 3 Evaluation use case scale and conventions 1≤n≤500, matrix elements are positive integers not exceeding 1000. |
import java.util.Scanner;
public class Z字形扫描201412_2 {
/*
* 思路是要利用好行号,找规律 分奇偶行分别处理 分上下部分分别处理
* */
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[][] a=new int[n+1][n+1];
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
a[i][j]=sc.nextInt();
}
}
for(int k=1;k<=n;k++){
if(k%2==1){
for(int i=k;i>=1;i--){
System.out.print(a[i][k-i+1]+" ");
}
}else{
for(int i=1;i<=k;i++){
System.out.print(a[i][k-i+1]+" ");
}
}
}
for(int k=n+1;k<=2*n-1;k++){
if(k%2==1){
for(int i=n;i>=k-(n-1);i--){
System.out.print(a[i][k-i+1]+" ");
}
}else{
for(int i=k-(n-1);i<=n;i++){
System.out.print(a[i][k-i+1]+" ");
}
}
}
}
}