CCF CSP Brush Question Record 6-201412-2 Z-shaped Scan (Java)

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:

  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 scan program, given an n×n matrix, output the zigzag scan of this matrix the result of.

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, which 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.

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

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]+" ");
					}
			}
		}
		
	}
}

 

Guess you like

Origin blog.csdn.net/m0_37483148/article/details/108288062