問題描述
給定一個矩陣matrix, 按照“之” 字形的方式打印這個矩陣
例如:給定一個矩陣:
則依次打印出的數字爲:
1 2 5 9 6 3 4 7 10 13 14 11 8 12 15 16
算法思路
先貼出一張4 X 4的矩陣之子打印的流程圖,會比較方便理解
算法代碼
public class _03_之字形打印 {
public static void main(String[] args) {
int[][] matrix = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
printZig(matrix);
}
private static void printZig(int[][] matrix) {
int row = 0,col = 0;
int m = matrix.length;
int n = matrix[0].length;
boolean up = true;//從左下到右上
while (row < m && col < n) {
System.out.print(matrix[row][col]+" ");
if (up) {//從左下到右上
if (row == 0 && col < n - 1) {//現在在第一行,只能向右走
up = !up;
col ++;
continue;
} else if (col == n - 1 && row > 0) {//現在在最後一列,只能向下走
up = !up;
row ++;
continue;
} else {//繼續走上坡
row --;
col ++;
}
} else {//從右上到左下
if (col == 0 && row < m - 1) {//現在在第一列,只能向下走
up = !up;
row ++;
continue;
} else if(row == m - 1 && col < n - 1) {//現在在最後一行,只能向右走
up = !up;
col ++;
continue;
} else {//繼續走下坡
row ++;
col --;
}
}
}
}
}