CCF之Z形扫描

这道题说白了就是找规律,根据前一步的移动方向来确定下一步的移动方向,是否到到最顶行/最底行?是否到达第一列/最后一列?根据这些条件来判断下一步的移动方向,刚开始没想清楚,看了别人的代码之后觉得豁然开朗,为大神打call

代码如下:

package Online_pra;

import java.util.Scanner;

public class CCF1412_2 {
	public static final int right=1;
	public static final int down=2;
	public static final int rightup=3;
	public static final int leftdown=4;
	
	public static void main(String args[]) {
		Scanner scan=new Scanner(System.in);
		int n=scan.nextInt();
		int a[][]=new int[n][n];
		for(int i=0;i<n;i++) {
			for(int j=0;j<n;j++)
				a[i][j]=scan.nextInt();
		}
		
		int row=0;
		int col=0;
		int direction=right;
		while(row!=n-1||col!=n-1) {
			System.out.print(a[row][col]+" ");
			switch(direction) {
			case right:
				col++;
				if(row==0)
					direction=leftdown;
				else
					direction=rightup;
				break;
			case down:
				row++;
				if(col==0)
					direction=rightup;
				else
					direction=leftdown;
				break;
			case rightup:
				row--;
				col++;
				if(row==0&&col!=n-1)
					direction=right;
				else if(col==n-1)
					direction=down;
				else
					direction=rightup;
				break;
			case leftdown:
				row++;
				col--;
				if(col==0&&row!=n-1)
					direction=down;
				else if(row==n-1)
					direction=right;
				else
					direction=leftdown;
				break;
			}
		}
		System.out.print(a[n-1][n-1]);
		System.out.println();
	}

}

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