之字形列印矩陣(Java)
阿新 • • 發佈:2019-01-05
import java.util.Scanner; public class Main { // 方向列舉 enum Direction{ DOWN, RIGHT_UP, RIGHT, LEFT_DOWN } public static void main(String[] args) { // TODO Auto-generated method stub int N, M; int[][] a; Scanner scan = new Scanner(System.in); N = scan.nextInt(); M = scan.nextInt(); a = new int[N][M]; for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { a[i][j] = scan.nextInt(); } } int row = 0, col = 0; Direction dir = Direction.DOWN; System.out.print(a[row][col] + " "); while(!(row == N - 1 && col == M - 1)) { switch(dir) { case DOWN: // 向下走 if(row < N - 1) { row++; System.out.print(a[row][col] + " "); if(col != M - 1) { dir = Direction.RIGHT_UP; } else { dir = Direction.LEFT_DOWN; } } else { dir = Direction.RIGHT; } break; case RIGHT_UP: // 向右上方向走 while(row > 0 && col < M - 1) { row--; col++; System.out.print(a[row][col] + " "); } if(row != 0) { dir = Direction.DOWN; } else { dir = Direction.RIGHT; } break; case RIGHT: // 向右走 if(col < M - 1) { col++; System.out.print(a[row][col] + " "); if(row != N - 1) { dir = Direction.LEFT_DOWN; } else { dir = Direction.RIGHT_UP; } } else { dir = Direction.DOWN; } break; case LEFT_DOWN: // 向左下方向走 while(col > 0 && row < N - 1) { row++; col--; System.out.print(a[row][col] + " "); } if(col != 0) { dir = Direction.DOWN; } else { dir = Direction.RIGHT; } break; } } } }
執行結果截圖: