这道题的关键是将数组的打印分为多个对角线的打印,在对角线的打印是双向的
且用一个boolean类型的变量用来控制是从上到下,还是从下到上
//答应对角线上的元素,可以从右上到左下,Up为true,从左下到右上,false为左下到右上
//给定一个右上角的点和左下角的点
public static void printLevel(int[][] m, int row1, int col1, int row2, int col2,
boolean f) {
if (f) {
while (row1!=row2+1) {//row1 != row2 + 1
System.out.print(m[row1++][col1--] + " ");
}
} else {
while (row2!=row1-1) {//
System.out.print(m[row2--][col2++] + " ");
}
}
}
而整体的打印的是用二个点,分别开始指向数组第一个点,一个往右运动再往下运动完,一个往下运动再往右运动完
这样每次二个点都可以形成对角线,也就能依次将数组按之字型打印了。
public class ZigPrintArray {
public static void printMatrixZigZag(int[][] matrix) {
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;
while (row1 != endR + 1) {
printLevel(matrix, row1, col1, row2, col2, fromUp);
row1 = col1 == endC ? row1 + 1 : row1;
col1 = col1 == endC ? col1 : col1 + 1;
col2 = row2 == endR ? col2 + 1 : col2;
row2 = row2 == endR ? row2 : row2 + 1;
fromUp = !fromUp;
}
System.out.println();
}
//答应对角线上的元素,可以从右上到左下,Up为true,从左下到右上,false为左下到右上
//给定一个右上角的点和左下角的点
public static void printLevel(int[][] m, int row1, int col1, int row2, int col2,
boolean f) {
if (f) {
while (row1!=row2+1) {//row1 != row2 + 1
System.out.print(m[row1++][col1--] + " ");
}
} else {
while (row2!=row1-1) {//
System.out.print(m[row2--][col2++] + " ");
}
}
}
public static void main(String[] args) {
int arr[][]=new int[][] {{1,2,3},{4,5,6,},{7,8,9}};
printMatrixZigZag(arr);
}
}