剑指offer第二版——面试题29(java)

面试题29:顺时针打印矩阵

题目:输入一个矩阵,按照从外向里的顺序依次打印出每一个数字

思路

分解为从外向里的顺指针圈打印

1. 打印圈数为min(cols/2+cols%2,rows/2+rows%2)   ——需要考虑行数和列数的奇偶性

如:



 

2. 每一圈打印分四步:

1)圈的最上面一行,从左到右打印

2)圈的最右边一列,从上到下打印

3)圈的最下面一列,从右到左打印

4)圈的最左边一列,从下到上打印

 

【!!!】其中需要注意的是3)和4)在只有一行或一列时的情况

当最后一圈只剩一行时,1)之后会直接跳到3),如果3)中没有判断 if(up==down) { break; } 则打印完最后一个数之后,会再重新打印左边的数字

同理,当最后一圈啊只剩一列时,如果不判断左右index是否相同,则打印完最后一个数之后,会再重新打印上面的数字

public class Q29 {
	public static void main(String[] args) {
		int[][] matrix  = new int[][]{{1,2,3},{4,5,6},{9,10,11},{2,3,1}};
		printMatrix(matrix);
	}
	
	public static void printMatrix(int[][] matrix) {
		int rows = matrix.length;
		int cols = 0;
		int round = 0;

		if(rows!=0) {
			cols = matrix[0].length;
			if(rows==1 && cols==1) {
				System.out.println(matrix[0][0]);
			}else {
				if(rows/2 +rows%2 >cols/2+cols%2) {
					round = cols/2+cols%2;
				}else {
					round = rows/2+rows%2;
				}
				System.out.printf("%d*%d\nround:%d",rows,cols,round);
				
				for(int i = 0;i<round;i++) {
					System.out.printf("\n---round:%d---\n",i+1);
					printRound(matrix,i,rows,cols);
				}
			}
		}
	}
	
	public static void printRound(int[][] matrix,int ind,int rows,int cols) {
		int left = ind;
		int right = cols-1-ind;
		int up = ind;
		int down = rows-1-ind;
		
		int loc = left;
		while(loc!=right) {
			System.out.printf("%d ", matrix[up][loc]);
			loc++;
		}
		
		loc = up;
		while(loc!=down) {
			System.out.printf("%d ", matrix[loc][right]);
			loc++;
		}
		
		loc = right;
		while(loc!=left) {
			System.out.printf("%d ", matrix[down][loc]);
			if(up==down) {
				break;
			}
			loc--;
		}
		
		loc = down;
		while(loc!=up ) {
			System.out.printf("%d ", matrix[loc][left]);
			if(left==right) {
				break;
			}
			loc--;
		}
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值