十九:“之”字形打印矩阵

题目

用zigzag的方式打印矩阵, 比如如下的矩阵
0 1 2 3
4 5 6 7
8 9 10 11
打印顺序为: 0 1 4 8 5 2 3 6 9 10 7 11

实现

import java.util.*;

public class Main {
    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        int[][] arr = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j] = in.nextInt();
            }
        }

        f(arr);        
    }
    
    //两个点,a和b,刚开始,a往下走,b往右走,最后a右走,b往下走,到最后位置
    //一个变量控制从下往上打印,还是从上往下打印
    public static void f(int[][] m) {
        int ah = 0;
        int al = 0;
        int bh = 0;
        int bl = 0;
        boolean downUp = true;
        int row = m.length;
        int col = m[0].length;
        while (al != col && bh != row) {
            printEdge(m, ah, al, bh, bl, downUp);
            al = ah == row - 1 ? al + 1 : al;
            ah = ah == row - 1 ? ah : ah + 1;
            bh = bl == col - 1 ? bh + 1 : bh;
            bl = bl == col - 1 ? bl : bl + 1;
            downUp = !downUp;
        }
    }
    
    public static void printEdge(int[][] m, int ah, int al, int bh, int bl, boolean downUp) {
        //从下往上打印,对于a点来说,a点的行数ah在不断你的变化
        if (downUp) {
            while (ah != bh - 1) {
                System.out.print(m[ah--][al++] + " ");
            }
        } else { //从上往下打印,对于b点来说,b的行在不断的增加,列在不断的减小
            while (bh != ah + 1) {
                System.out.print(m[bh++][bl--] + " ");
            }
            
        }
    }
}

你可能感兴趣的:(算法)