算法——“Z”型打印矩阵 - Go语言中文社区

算法——“Z”型打印矩阵


【题目】 给定一个矩阵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);
	}
}
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_31851531/article/details/96974861
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-04-18 14:01:43
  • 阅读 ( 1097 )
  • 分类:算法

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢