矩阵--“之”字形打印矩阵

 给定一个矩阵matrix, 按照“之” 字形的方式打印这个矩阵, 例如: 1 2 3 4 5 6 7 8 9 10 11 12
“之” 字形打印的结果为: 1, 2, 5, 9, 6, 3, 4, 7, 10, 11,8, 12
【要求】 额外空间复杂度为O(1)。


解:有可能不是正方形,可能是矩形,所以要分别有两组坐标来代表左右的变化

先是row1和col2变化,当row1==row-1时,col1变化;col2==col-1时,row2变化

注意一点是:在进行如下操作时,前边的两组,判断条件是row1,且它还要变化,所以应该是col1先使用条件

下边两组同理。

col1 = row1 < row - 1 ? col1 : col1 + 1;
row1 = row1 < row - 1 ? row1 + 1 : row1;
row2 = col2 < col - 1 ? row2 : row2 + 1;
col2 = col2 < col - 1 ? col2 + 1 : col2;

 

 完整代码如下:

public class ZhiPrintSquare {
    public static void printMatrix(int[][] arrays){
        int row = arrays.length;
        int col = arrays[0].length;
        int row1 = 0;
        int col1 = 0;
        int row2 = 0;
        int col2 = 0;
        boolean flag = true;

        while(col1 < col){
            printLevel(arrays, row1, col1, row2, col2, flag);
            col1 = row1 < row - 1 ? col1 : col1 + 1;
            row1 = row1 < row - 1 ? row1 + 1 : row1;
            row2 = col2 < col - 1 ? row2 : row2 + 1;
            col2 = col2 < col - 1 ? col2 + 1 : col2;
            flag = !flag;
        }
    }

    public static void printLevel(int[][] arrays, int row1, int col1, int row2, int col2, boolean flag){
        //flag=true从下往上
        if(flag){
            while(col1 <= col2){
                System.out.print(arrays[row1--][col1++] + " ");
            }
        }else{
            //flag=false 从上往下
            while(col2 >= col1){
                System.out.print(arrays[row2++][col2--] + " ");
            }
        }
    }
    public static void print(int[][] arrays){
        for(int i = 0; i < arrays.length; i++){
            for(int j = 0; j < arrays[0].length; j++){
                System.out.print(arrays[i][j]  + " ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args){
        int[][] arrays = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}, {17,18,19,20}};
        print( arrays );
        printMatrix( arrays );
    }
}

  

转载于:https://www.cnblogs.com/SkyeAngel/p/8745955.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值