/**
* Z字型打印矩阵
* 1 2 3 4
* 5 6 7 8
* 9 10 11 12
* 13 14 15 16
*
* 1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16
*/
public class TwoArraysTest03 {
public static void main(String[] args) {
TwoArraysTest03 twoArraysTest03 = new TwoArraysTest03();
int [][]matrix = new int[4][4];
int temp = 0 ;
for (int[] ints : matrix) {
for (int i = 0; i < ints.length; i++) {
ints[i] = temp+1;
temp++;
}
}
twoArraysTest03.zPlainMatrix(matrix);
}
public void zPlainMatrix(int [] [] matrix){
int row = 0,rowMax = matrix.length;
int col = 0,colMax = matrix[0].length;
// 若为true 就从左下向右上打印(走上坡),反正右上向左下打印(走下坡)
boolean liftToRight = true;
while (row < rowMax && col <colMax){
// 走上坡
// 结果两种情况 第一种:这波上坡走完的时候的第一行
// ----右走一步 col++;
// 另一种:这波上坡走完的时候在最后一列
// ----下走一步 row++;
if (liftToRight){
System.out.print(matrix[row][col]+"\t");
// 第一种
if (row == 0 && col < colMax-1){
// 右走一步 便于下一波的下坡
col++;
// 方向切换
liftToRight = false;
continue;
// 第二种
}else if (row > 0 && col == colMax-1){
// 下走一步
row++;
// 切换方向
liftToRight = false;
continue;
// 走上坡的路上
}else {
row--;
col++;
}
// 走下坡
// 结果两种情况
// 第一种:这波下坡走完在第一列
// ----下走一步 row++;
// 第二种:这波下坡走完在最后一行
// ----右走一步 col++;
}else {
System.out.print(matrix[row][col]+"\t");
// 第一种
if (col == 0 && row < rowMax-1){
row++;
liftToRight = true;
continue;
// 第二种
}else if ( row == rowMax-1){
col++;
liftToRight = true;
continue;
// 在走下坡的路上
}else {
row++;
col--;
}
}
}
}
}