“之”字形打印矩阵------牛客网初级班练习8

【题目】 给定一个矩阵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)。

思路

准备俩个点A,B
A每次向右走,遇到最右边则向下走

B每次向下走,遇到最下边则向右走

A,B每次只各走一步

public static void printMatrixZigZag(int[][] matrix) {
   int tR = 0;
   int tC = 0;
   int dR = 0;
   int dC = 0;
   int endR = matrix.length - 1;
   int endC = matrix[0].length - 1;
   boolean fromUp = false;
   //如果tR来到最后一行就停止
   while (tR != endR + 1) {
      //有了俩点以及一个boolean值之后,如何打印这条对角线
      printLevel(matrix, tR, tC, dR, dC, fromUp);
      //如果a没有来到最后一列,a的行号不变tC == endC ? tR + 1 : tR
      tR = tC == endC ? tR + 1 : tR;
      //如果a的列数没有来到最后一行,a往右
      tC = tC == endC ? tC : tC + 1;
      
      dC = dR == endR ? dC + 1 : dC;
      dR = dR == endR ? dR : dR + 1;
      fromUp = !fromUp;
   }
   System.out.println();
}

public static void printLevel(int[][] m, int tR, int tC, int dR, int dC,
      boolean f) {
   if (f) {
      while (tR != dR + 1) {
         System.out.print(m[tR++][tC--] + " ");
      }
   } else {
      while (dR != tR - 1) {
         System.out.print(m[dR--][dC++] + " ");
      }
   }
}

猜你喜欢

转载自blog.csdn.net/qq_43193797/article/details/86759092