1. 程式人生 > 其它 >Leetcode刷題54. 螺旋矩陣

Leetcode刷題54. 螺旋矩陣

技術標籤:陣列、連結串列、跳錶陣列

給定一個包含m x n個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。

示例1:

輸入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
輸出: [1,2,3,6,9,8,7,4,5]
示例2:

輸入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
輸出: [1,2,3,4,8,12,11,10,9,5,6,7]

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/spiral-matrix
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

class Solution {
    //定義4個變數,分別從矩陣的上下左右進行遍歷
    //時間複雜度O(m*n),空間複雜度O(1)
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return result;

        //定義變數
        int left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1;
        while (left <= right && top <= bottom) {
            //從左到右
            for (int col = left; col <= right; col++) {
                result.add(matrix[top][col]);
            }
            top++;
            //從上到下
            for (int row = top; row <= bottom; row++) {
                result.add(matrix[row][right]);
            }
            right--;
            //從右到左
            if (top <= bottom) {
                for (int col = right; col >= left; col--) {
                    result.add(matrix[bottom][col]);
                }
            }
            bottom--;
            //從下到上
            if (left <= right) {
                for (int row = bottom; row >= top; row--) {
                    result.add(matrix[row][left]);
                }
            }
            left++;
        }
        return result;
    }
}