剑指offer-顺时针打印矩阵
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
首先判断需要走几圈,然后每圈依次按照向右向下向左向上的顺序遍历
1 public ArrayList<Integer> printMatrix(int [][] matrix) {//my 2 int rowlength = matrix.length; 3 int collength = matrix[0].length; 4 int count = ((rowlength<collength?rowlength:collength)-1)/2+1; 5 ArrayList<Integer> result = new ArrayList<Integer>(); 6 for (int i = 0; i < count; i++) { 7 for (int j = i; j < collength-i; j++) {//向右 8 result.add(matrix[i][j]); 9 } 10 for (int j = i+1; j < rowlength-i; j++) {//向下 11 result.add(matrix[j][collength-i-1]); 12 } 13 for (int j = collength-i-2; j >= i&&(rowlength-i-1)>i; j--) {//向左 注意判断i的值 14 result.add(matrix[rowlength-i-1][j]); 15 } 16 for (int j = rowlength-i-2; j > i &&(collength-i-1)>i; j--) {//向上 注意判断i的值 17 result.add(matrix[j][i]); 18 } 19 } 20 return result; 21 }