社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
【题目】 给定一个矩阵matrix,按照“Z”字形的方式打印这个矩阵,例如:
1 2 3 4
5 6 7 8
9 10 11 12
“Z”字形打印的结果为:1,2,5,9,6,3,4,7,10,11,8,12
【要求】 额外空间复杂度为O(1)。
这道题不能单纯的去找下标之间的关系,否则会很复杂,应该从宏观角度去考虑这道题,我们设置两个点,都从1这里出发,A每次向右移动一个点,碰到最有边界向下走,B点每次向下走一个点,碰到下边界向右走,就能发现每次移动一个点之后,AB总能连成一条线,并且就是我们要求的Z,我们就只需要再设定一个bool值来判断我们该从上往下读还是从下往上读。
代码如下:
public class ZigZagPrintMatrix {
public static void printMatrixZigZag(int[][] matrix) {
// 设置两个点,给定初始值
int aX = 0;
int aY = 0;
int bX = 0;
int bY = 0;
// 找到边界
int endRow = matrix.length - 1; // 行
int endCol = matrix[0].length - 1; // 列
// false从下往上,true从上往下,因为读完第一个数我们要从上往下走,所以初始值为false
boolean fromUp = false;
while (aX != endRow + 1) {
printLevel(matrix, aX, aY, bX, bY, fromUp);
// 每个点每次移动一格的代码
aX = aY == endCol ? aX + 1 : aX;
aY = aY == endCol ? aY : aY + 1;
bY = bX == endRow ? bY + 1 : bY;
bX = bX == endRow ? bX : bX + 1;
fromUp = !fromUp;
}
}
// 打印AB连线上的所有的数
public static void printLevel(int[][] m, int aX, int aY, int bX, int bY, boolean f) {
if (f) {
// 从上往下打印
while (aX != bX + 1) {
System.out.print(m[aX++][aY--] + " ");
}
} else {
// 从下往上打印
while (bX != aX - 1) {
System.out.print(m[bX--][bY++] + " ");
}
}
}
public static void main(String[] args) {
int[][] matrix = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
printMatrixZigZag(matrix);
}
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!