按“之”字形顺序打印矩阵(算法)

题目:给定一个矩阵matrix,按照“之”字形的方式打印这个矩阵,例如:

在这里插入图片描述

打印结果为:4,5,6,1,6,6,9,3,7。
要求额外空间复杂度为O(1)。

算法思想:打印“之”字形数字

算法思想:根据上例容易观察出之字形可以拆分成打印上图直线上的数字,只需将打印方向改变就可以满足题目要求。设置两个初始点A和B,同时让点A向右移动,点B向下移动,当A移动到右边界时再继续向下移动,当B移动到下边界时再向右移动。A和B每移动一次就打印AB直接上的数字,退出条件为row1>endR或col2>endC。

代码如下:

package test_class_03;

public class ZigZagPrintMatrix {
	
	public static void printMatrixZigZag(int [][]m){
		//定义A,B两个初始点以及终点End
		int row1=0;
		int col1=0;
		int row2=0;
		int col2=0;
		int endR=m.length-1;
		int endC=m[0].length-1;
		boolean fromup=false;
		while(row1!=endR+1){
			printLine(m,row1,col1,row2,col2,fromup);
			row1=col1==endC?row1+1:row1;      //A点刚开始移动时是行不变列 变,所以更新时应该将不变的行row1放在前面。
			col1=col1==endC?col1:col1+1;
			col2=row2==endR?col2+1:col2;      //B点刚开始移动时是行变列不变,所以更新时应该将不变的列col2放在前面。
			row2=row2==endR?row2:row2+1;
			fromup=!fromup;
		}
		System.out.println();
	}
	
	public static void printLine(int [][]m,int row1,int col1,int row2,int col2,boolean fromup){
		if(fromup){
			while(row1!=row2+1){
				System.out.print(m[row1++][col1--]+" ");
			}
		}else{
			while(row2!=row1-1){
				System.out.print(m[row2--][col2++] + " ");
			}
		}
	}
	public static void main(String[] args) {
		int [][]m={{4,5,6},{6,6,9},{1,3,7}};
		printMatrixZigZag(m);
	}
}

发布了17 篇原创文章 · 获赞 60 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_36744540/article/details/89762630
今日推荐