54. 螺旋矩阵

https://leetcode-cn.com/problems/spiral-matrix/

执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:6.5 MB, 在所有 C++ 提交中击败了92.75%的用户

由于每一圈的loop范围可以由左上角坐标和右下角坐标确定,因此可以由这两个坐标值控制大循环,在每次循环内,分四个方向转圈打印,要特别注意的是当只剩一行或一列的时候,要在合适的位置break


每一圈依次在四个方向打印
class Solution {
public:
    vector spiralOrder(vector>& matrix) {
        vector ret;
        int rows = matrix.size();
        int cols = matrix[0].size();

        int left = 0;
        int top = 0;
        int right = cols - 1;
        int bottom = rows - 1;
        while (left <= right && top <= bottom) {
            // 从左到右
            for (int i = left; i <= right; ++i) {
                ret.push_back(matrix[top][i]);
            }
            if (top == bottom)  break;
            // 从上到下
            for (int i = top + 1; i <= bottom - 1; ++i) {
                ret.push_back(matrix[i][right]);
            }
            // 从右到左
            for (int i = right; i >= left; --i) {
                ret.push_back(matrix[bottom][i]);
            }
            if (left == right)  break;
            // 从下到上
            for (int i = bottom - 1; i >= top + 1; --i) {
                ret.push_back(matrix[i][left]);
            }
            ++left;
            ++top;
            --right;
            --bottom;
        }

        return ret;
    }
};

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