剑指Offer之之字行打印矩阵

这道题的关键是将数组的打印分为多个对角线的打印,在对角线的打印是双向的

且用一个boolean类型的变量用来控制是从上到下,还是从下到上

//答应对角线上的元素,可以从右上到左下,Up为true,从左下到右上,false为左下到右上
	//给定一个右上角的点和左下角的点
	public static void printLevel(int[][] m, int row1, int col1, int row2, int col2,
			boolean f) {
		if (f) {
			while (row1!=row2+1) {//row1 != row2 + 1
				System.out.print(m[row1++][col1--] + " ");
			}
		} else {
			while (row2!=row1-1) {//
				System.out.print(m[row2--][col2++] + " ");
			}
		}
	}

而整体的打印的是用二个点,分别开始指向数组第一个点,一个往右运动再往下运动完,一个往下运动再往右运动完

这样每次二个点都可以形成对角线,也就能依次将数组按之字型打印了。

public class ZigPrintArray {
	public static void printMatrixZigZag(int[][] matrix) {
		int row1 = 0;
		int col1 = 0;
		int row2 = 0;
		int col2 = 0;
		int endR = matrix.length - 1;//行数
		int endC = matrix[0].length - 1;//列数																																								
		boolean fromUp = false;
		while (row1 != endR + 1) {
			printLevel(matrix, row1, col1, row2, col2, fromUp);
			row1 = col1 == endC ? row1 + 1 : row1;
			col1 = col1 == endC ? col1 : col1 + 1;
			col2 = row2 == endR ? col2 + 1 : col2;
			row2 = row2 == endR ? row2 : row2 + 1;
			fromUp = !fromUp;
		}
		System.out.println();
	}
	//答应对角线上的元素,可以从右上到左下,Up为true,从左下到右上,false为左下到右上
	//给定一个右上角的点和左下角的点
	public static void printLevel(int[][] m, int row1, int col1, int row2, int col2,
			boolean f) {
		if (f) {
			while (row1!=row2+1) {//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 arr[][]=new int[][] {{1,2,3},{4,5,6,},{7,8,9}};
		printMatrixZigZag(arr);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值