54. Spiral Matrix/螺旋矩阵

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

AC代码

class Solution {
public:
    vector spiralOrder(vector>& matrix) {
        if (matrix.empty()) return {};
        vector v;
        int left = 0, right = matrix[0].size() - 1, up = 0,
            down = matrix.size() - 1;
        int i = 0, j = 0,sum=matrix.size() * matrix[0].size();
        while (true) {
            while (j <= right) v.push_back(matrix[i][j++]);
            if (v.size() == sum) break;
            j--;
            up++;
            v.pop_back();
            while (i <= down) v.push_back(matrix[i++][j]);
            if (v.size() == sum) break;
            i--;
            right--;
            v.pop_back();
            while (j >= left) v.push_back(matrix[i][j--]);
            if (v.size() == sum) break;
            j++;
            down--;
            v.pop_back();
            while (i >= up) v.push_back(matrix[i--][j]);
            if (v.size() == sum) break;
            i++;
            left++;
            v.pop_back();
        }
        return v;
    }
};

总结

空间复杂度有点高

你可能感兴趣的:(54. Spiral Matrix/螺旋矩阵)