美文网首页
54. Spiral Matrix/螺旋矩阵

54. Spiral Matrix/螺旋矩阵

作者: 蜜糖_7474 | 来源:发表于2019-05-23 09:32 被阅读0次

    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<int> spiralOrder(vector<vector<int>>& matrix) {
            if (matrix.empty()) return {};
            vector<int> 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/螺旋矩阵

          本文链接:https://www.haomeiwen.com/subject/mugmzqtx.html