【剑指29】顺时针打印矩阵

方法一:模拟路径:时间O(nm),空间O(1)

题解:

  1. 模拟矩阵的遍历方法,按层划分,一层一层的打印,直到打印完最内层的元素
  2. 从左到右遍历上侧元素,依次为(top, left) 到 (top, right)
  3. 从上到下遍历右侧元素,依次为(top + 1, right) 到 (bottom, right)
  4. 如果 left <right && top < bottom 说明可以向左遍历,依次为(bottom, right - 1) 到 (bottom, left + 1)。也可以向上遍历,依次为(bottom, left) 到 (top + 1, left)

在这里插入图片描述

class Solution {
    
    
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) 
    {
    
    
        vector<int> board;
        if (matrix.empty())
            return board;
        int top = 0, bottle = matrix.size() - 1, left = 0, right = matrix[0].size() - 1;
        while (top <= bottle && left <= right)
        {
    
    
            for (int j = left; j <= right; j++)
            {
    
    
                board.push_back(matrix[top][j]);
            }
            for (int i = top + 1; i <= bottle; i++)
            {
    
    
                board.push_back(matrix[i][right]);
            }
            if (top < bottle && left < right)
            {
    
    
                for (int j = right - 1; j > left; j--)
                {
    
    
                    board.push_back(matrix[bottle][j]);
                }
                for (int i = bottle; i > top; i--)
                {
    
    
                    board.push_back(matrix[i][left]);
                }    
            }
            top++;
            left++;
            bottle--;
            right--;
        }
        return board;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_45691748/article/details/113866956
今日推荐