思路:在(0,0)处,设置两个点,一个点a,一个点b,a和b同时移动,a向右移动,移到边界后向下移动,b向下移动,移动边界后向右移动,结束条件是a或者b到达矩阵的右下顶点,每次移动后就打印ab两点连线
public class ZigZagPrintMatrix { public static void main(String[] args) { int[][] matrix = { { 1, 2, 3, 4 , 20 }, { 5, 6, 7, 8 , 21 }, { 9, 10, 11, 12 , 22 }, { 13, 14, 15, 16 , 23 } }; print(matrix); //printLine(matrix,2,3,3,2,true); } public static void print(int[][] matrix) { int aR = 0; int aC = 0; int bR = 0; int bC = 0; boolean flag = false; while (aR != matrix.length || bC != matrix[0].length) { // System.out.println("(" +aR +","+ aC + ") " + "(" +bR+","+ bC + ") " ); // 先打印 printLine(matrix, aR, aC, bR, bC, flag); if (aR == 0 && aC < matrix[0].length - 1) { // 列逐渐增加 aC += 1; } else if (aR == 0 && aC == matrix[0].length - 1) { // 到达顶点后行增加 aR += 1; } else { // 行继续增加,直到aR = matrix.length跳出循环 aR += 1; } if (bC == 0 && bR < matrix.length - 1) { bR += 1; } else if (bC == 0 && bR == matrix.length - 1) { bC++; } else { bC++; } flag = !flag; } } private static void printLine(int[][] matrix, int aR, int aC, int bR, int bC, boolean flag) { if (flag) { // 从右上向左下打印 while (aR <= bR) { System.out.print(matrix[aR++][aC--] + " "); } } else { // 从左下向右上打印 while (bC <= aC) { System.out.print(matrix[bR--][bC++] + " "); } } } }