天天看點

[劍指offer] 順時針列印矩陣

題目描述

輸入一個矩陣,按照從外向裡以順時針的順序依次列印出每一個數字,例如,如果輸入如下矩陣:

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

.

解題思路

先得到矩陣的行和列數,然後依次旋轉列印資料,一次旋轉列印結束後,往對角分别前進和後退一個機關。

要注意單行和單列的情況。

參考代碼

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;
        ArrayList<Integer> res = new ArrayList<>();
        
        if(row == 0 && col == 0)
            return res;
        int left = 0, right = col - 1, top = 0, bottom = row - 1;
        while(left <= right && top <= bottom){
            //上:從左到右
            for(int i=left; i<=right; i++)
                res.add(matrix[top][i]);
            //右:從上到下
            for(int i=top+1; i<=bottom; i++)
                res.add(matrix[i][right]);
            //下:從右到左
            if(top != bottom){
                //防止單行情況
                for(int i=right-1; i>=left; i--)
                    res.add(matrix[bottom][i]);
            }
            //左:從下到上
            if(left != right){
                //防止單列情況
                for(int i=bottom-1; i>top; i--)
                    res.add(matrix[i][left]);
            }
            left++; right--; top++; bottom--;
        }
        return res;
    }
}
           

繼續閱讀