算法练习题(六)——Z字型打印矩阵

/**
 *  Z字型打印矩阵
 *  1	2	3	4
 *  5	6	7	8
 *  9	10	11	12
 *  13	14	15	16
 *
 *  1	2	5	9	6	3	4	7	10	13	14	11	8	12	15	16
 */
public class TwoArraysTest03 {
    public static void main(String[] args) {
        TwoArraysTest03 twoArraysTest03 = new TwoArraysTest03();
        int [][]matrix = new int[4][4];
        int temp = 0 ;
        for (int[] ints : matrix) {
            for (int i = 0; i < ints.length; i++) {
                ints[i] = temp+1;
                temp++;
            }
        }
        twoArraysTest03.zPlainMatrix(matrix);
    }
    public void zPlainMatrix(int [] [] matrix){
        int row = 0,rowMax = matrix.length;
        int col = 0,colMax = matrix[0].length;
//        若为true 就从左下向右上打印(走上坡),反正右上向左下打印(走下坡)
        boolean liftToRight = true;
        while (row < rowMax && col <colMax){
//          走上坡
//            结果两种情况  第一种:这波上坡走完的时候的第一行 
//                          ----右走一步 col++;
//                     另一种:这波上坡走完的时候在最后一列
//                          ----下走一步 row++;
            if (liftToRight){
                System.out.print(matrix[row][col]+"\t");
//                第一种
                if (row == 0 && col < colMax-1){
//                  右走一步 便于下一波的下坡
                    col++;
//                  方向切换
                    liftToRight = false;
                    continue;
//                第二种
                }else if (row > 0 && col == colMax-1){
//                  下走一步
                    row++;
//                  切换方向
                    liftToRight = false;
                    continue;
//                走上坡的路上
                }else {
                    row--;
                    col++;
                }
//          走下坡
//             结果两种情况
//                  第一种:这波下坡走完在第一列
//                       ----下走一步 row++;
//                  第二种:这波下坡走完在最后一行
//                       ----右走一步 col++;
            }else {
                System.out.print(matrix[row][col]+"\t");
//                第一种
                if (col == 0 && row < rowMax-1){
                    row++;
                    liftToRight = true;
                    continue;
//                第二种
                }else if ( row == rowMax-1){
                    col++;
                    liftToRight = true;
                    continue;
//                在走下坡的路上
                }else {
                    row++;
                    col--;
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值