多维数组与矩阵之之字形打印矩阵
问题描述
给定一个矩阵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 --;
}
}
}
}
}