试题编号: | 201412-2 |
试题名称: | Z字形扫描 |
时间限制: | 2.0s |
内存限制: | 256.0MB |
问题描述: | 问题描述 在图像编码的算法中,需要将一个给定的方形矩阵进行Z字形扫描(Zigzag Scan)。给定一个n×n的矩阵,Z字形扫描的过程如下图所示: |
解题代码(java):
import java.util.Scanner; public class Main { 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 int data[][]; //矩阵 public static void main(String[] args) { new Main().run(); } public static void run(){ //接收输入 Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); data = new int[n][n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ data[i][j] = scanner.nextInt(); } } int row = 0; int col = 0; int direction =RIGHT; while (row != n - 1 || col != n - 1) { System.out.PRint(data[row][col]+" "); switch (direction) { case RIGHT: col++; if (row == 0) direction = LEFTDOWN; else direction = RIGHTUP; 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 DOWN: row++; if (col == 0) direction = RIGHTUP; else direction = LEFTDOWN; 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(data[n-1][n-1]); } }
新闻热点
疑难解答