1. 程式人生 > 其它 >leetcode——螺旋矩陣

leetcode——螺旋矩陣

技術標籤:面試C++

題目:給定一個包含mxn個元素的矩陣(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]

方案一:

class Solution {
    vector<vector<int>> delta = {{0,1}, {1,0}, {0,-1}, {-1, 0}};
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.size() == 0 || matrix[0].size() == 0) {
            return {};
        }
        int row = matrix.size(), col = matrix[0].size();
        int total = row * col;
        vector<int> res = vector<int>(total);
        vector<vector<int>> status = vector<vector<int>>(row, vector<int>(col, 0));
        int m = 0, n = 0;
        int direction = 0;
        for (int i = 0; i < total; i++) {
            res[i] = matrix[m][n];
            status[m][n] = 1;
            int nextM = m + delta[direction][0];
            int nextN = n + delta[direction][1];
            // 方向只會變化一次
            if (nextM >= 0 && nextM < row && nextN >= 0 && nextN < col && status[nextM][nextN] == 0) {
                m = nextM;
                n = nextN;
            } else {
                direction = (direction + 1) % 4;
                m += delta[direction][0];
                n += delta[direction][1];
            }
        }
        return res;
    }
};

時間複雜度O(mn)

空間複雜度O(mn)

方案二: