矩阵--“之”字形打印矩阵
给定一个矩阵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 ); } }