引用
给定一个矩阵matrix,按照“之”字形的方式打印这个矩阵。例如
1,8,6,7
2,6,4,11
3,5,9,10
打印结果是1,8,2,3,6,6,7,4,5,9,11,10。要求额外空间复杂度是O(1)。
思路
两个坐标进行记录,都从0,0点开始。一个往右移动,移动到最右往下移动;另一个往下移动,移动到最下往右移动,两个坐标始终处于一条斜线,然后打印斜线上的元素就行。
代码
public class ZigZagPrintMatrix {
// row1 col1往右走 走到头往下走
// row2 col2往下走 走到头往右走
// 始终处于一条斜线 打印斜线上的元素
public static void printMatrixZigZag(int[][] matrix){
// 都是从0,0 位置开始
int row1 =0;
int col1 = 0;
int row2 = 0;
int col2 = 0;
// 记录行边界
int endR = matrix.length-1;
// 记录列边界
int endC = matrix[0].length-1;
// 判断打印方向
boolean fromUp = false;
// row1越界停止,或者col2越界停止
while (row1 != endR+1) {
printLevel(matrix, row1, col1, row2, col2, fromUp);
// r