面试题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--;
}
}
}