package com.company;
import org.junit.jupiter.api.Test;
publicclassPrintMatrixZigZag {@TestpublicvoidtestPrint(){
int[][] a = {{1,2,3,4}, {5,6,7,8},{9,10,11,12},{13,14,15,16}};
printMatrix(a);
}
publicstaticvoidprintMatrix(int[][] num) {
int sx = 0;
int sy = 0;
int ex = num.length;
int ey = num[0].length;
boolean flag = true;
while (sy < ey) {
print(num, sx, sy, flag, sy, sx);
flag = !flag;
sy ++;
}
sy--;
while (sx < ex) {
print(num, sx, sy, flag, sy, sx);
flag = !flag;
sx ++;
}
}
privatestaticvoidprint(int[][] num, int x, int y, boolean flag, int x1, int y1) {
if (flag) {
/*===== 上到下 ======*/while (x1>=x && y1<=y) {
System.out.print("-"+num[x++][y--]+"-");
}
}else{
/*========下到上===*/while (x1>=x && y1<=y) {
System.out.print("-"+num[x1--][y1++]+"-");
}
}
System.out.println("");
}
}
代码二
package com.company;
import org.junit.jupiter.api.Test;
publicclassPrintMatrixZigZag {@TestpublicvoidtestPrint(){
int[][] a = {{1,2,3,4}, {5,6,7,8},{9,10,11,12},{13,14,15,16}};
printMatrix(a);
}
publicstaticvoidprintMatrix(int[][] num) {
int sx = 0;
int sy = 0;
int ex = num.length-1;
int ey = num[0].length-1;
boolean flag = true;
while (sx != ex) {
print(num, sx, sy, flag, sy, sx);
sx = sy == ey ? sx +1: sx;
sy = sy == ey ? sy : sy +1;
flag = !flag;
}
}
privatestaticvoidprint(int[][] num, int x, int y, boolean flag, int x1, int y1) {
if (flag) {
/*===== 上到下 ======*/while (x1>=x && y1<=y) {
System.out.print("-"+num[x++][y--]+"-");
}
}else{
/*========下到上===*/while (x1>=x && y1<=y) {
System.out.print("-"+num[x1--][y1++]+"-");
}
}
System.out.println("");
}
}