ccf认证Z字形扫描90分

《ccf认证Z字形扫描90分》

问题描述

试题编号: 201412-2
试题名称: Z字形扫描
时间限制: 2.0s
内存限制: 256.0MB
问题描述: 问题描述   在图像编码的算法中,需要将一个给定的方形矩阵进行Z字形扫描(Zigzag Scan)。给定一个n×n的矩阵,Z字形扫描的过程如下图所示:
《ccf认证Z字形扫描90分》
  对于下面的4×4的矩阵,
  1 5 3 9
  3 7 5 6
  9 4 6 4
  7 3 1 3
  对其进行Z字形扫描后得到长度为16的序列:
  1 5 3 9 7 3 9 5 4 7 3 6 6 4 1 3
  请实现一个Z字形扫描的程序,给定一个n×n的矩阵,输出对这个矩阵进行Z字形扫描的结果。 输入格式   输入的第一行包含一个整数n,表示矩阵的大小。
  输入的第二行到第n+1行每行包含n个正整数,由空格分隔,表示给定的矩阵。 输出格式   输出一行,包含n×n个整数,由空格分隔,表示输入的矩阵经过Z字形扫描后的结果。 样例输入 4
1 5 3 9
3 7 5 6
9 4 6 4
7 3 1 3 样例输出 1 5 3 9 7 3 9 5 4 7 3 6 6 4 1 3 评测用例规模与约定   1≤n≤500,矩阵元素为不超过1000的正整数。
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		int n=scanner.nextInt();
		int[][] arr=new int[n][n];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				arr[i][j]=scanner.nextInt();
			}
		}
		int[][] d={{0,1},{1,0},{-1,1},{1,-1}};
		int row=0;
		int column=0;
		int next=0;
		System.out.print(arr[row][column]+" ");
		row=row+d[next][0];
		column=column+d[next][1];
		System.out.print(arr[row][column]+" ");
		while (row!=n-1||column!=n-1) {
			if (next==0&&row==0) {
				next=3;
			}else if (next==0&&row==n-1) {
				next=2;
			}else if (next==1&&column==0) {
				next=2;
			}else if (next==1&&column==n-1) {
				next=3;
			}else if (next==2&&row!=0&&column!=n-1) {
				next=2;
			}else if (next==2&&column==n-1) {
				next=1;
			}else if (next==2&&row==0) {
				next=0;
			}else if (next==3&&row!=n-1&&column!=0) {
				next=3;
			}else if (next==3&&row==n-1) {
				next=0;
			}else if (next==3&&column==0) {
				next=1;
			}
			row=row+d[next][0];
			column=column+d[next][1];
			System.out.print(arr[row][column]+" ");
		}
	}
	
}

本来写了两个类,其中一个类存放方向,但是总是编译出错,后来换成了数组,虽然结果输出正确,但是只有90分,运行出错,不知道怎么错了。

    原文作者:Z字形编排问题
    原文地址: https://blog.csdn.net/m0_38103546/article/details/76597314
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞