劍指offer-19:順時針列印矩陣

不蛋定發表於2020-11-17

題目描述

輸入一個矩陣,按照從外向裡以順時針的順序依次列印出每一個數字,例如,如果輸入如下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.

解題思路

  • 按照順時針挨著解析矩陣
  • 注意邊界判斷,length需要減一,row和col可取

程式碼實現

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        if (matrix.length == 0 || matrix[0].length == 0) {
            return list;
        }
        
        int row = 0;
        int col = 0;
        int rowLength = matrix.length;
        int colLength = matrix[0].length;
        
        while (true) {
            for (int i = col; i < colLength; i++) {
                list.add(matrix[row][i]);
            }
            row++;
            if (rowLength <= row) break;
            for (int i = row; i < rowLength; i++) {
                list.add(matrix[i][colLength - 1]);
            }
            colLength--;
            if (col >= colLength) break;
            for (int i = colLength - 1; i >= col; i--) {
                list.add(matrix[rowLength - 1][i]);
            }
            rowLength--;
            if (rowLength <= row) break;
            for (int i = rowLength - 1; i >= row; i--) {
                list.add(matrix[i][col]);
            }
            col++;
            if (col >= colLength) break;
        }
         return list;
    }
}

相關文章