给定一个矩阵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
斜对角线,他们的的运行轨迹分别是 向右,不能动时向下; 另一个 先向下 不能动时向右
1 package my_basic.class_3; 2 3 /*之字形打印矩阵*/ 4 public class Code_08_ZipZagPrintMatrix { 5 public static void printMatrixZigZag(int[][] matrix) { 6 int tr = 0; 7 int tc = 0; 8 int dr = 0; 9 int dc = 0; 10 int endR = matrix.length-1; 11 int endC = matrix[0].length-1; 12 boolean fromUp = true; 13 while (tr != endR + 1) { 14 printLevel(matrix,tr,tc,dr,dc,fromUp); 15 tr = tc == endC ? tr + 1 : tr; 16 tc = tc == endC ? tc : tc + 1; 17 dc = dr == endR ? dc + 1 : dc; 18 dr = dr == endR ? dr : dr + 1; 19 fromUp = !fromUp; 20 } 21 } 22 23 private static void printLevel(int[][] matrix, int tr, int tc, int dr, int dc, boolean fromUp) { 24 if (fromUp) { 25 while (tr != dr+1) { 26 System.out.print(matrix[tr++][tc--] + " "); 27 } 28 }else { 29 while (dr != tr-1) { 30 System.out.print(matrix[dr--][dc++] + " "); 31 } 32 } 33 } 34 35 public static void main(String[] args) { 36 int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; 37 printMatrixZigZag(matrix); 38 39 } 40 41 }