29. 顺时针打印矩阵

1. 描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

2. 例子

示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

3. 限制

  • 0 <= matrix.length <= 100
  • 0 <= matrix[i].length <= 100

4. 题解

n 是 i_matrix 中的数字数
时间复杂度: O(n)
空间复杂度: O(n)

class Solution 
{
public:
    // vector<int> spiralOrder(vector<vector<int>>& matrix) 
    vector<int> spiralOrder(vector<vector<int>> &i_matrix) 
    {
        if(i_matrix.empty() || i_matrix.front().empty()) return vector<int>{};
        int leftBorder = 0, rightBorder = i_matrix.front().size() - 1, upBorder = 1, downBorder = i_matrix.size() - 1;
        int direction = (i_matrix.front().size() > 1 ? 0 : 1); // 0 1 2 3: right, down, left, up
        vector<int> result(i_matrix.size() * i_matrix.front().size());
        for(int i = 0, row = 0, column = 0; i < i_matrix.size() * i_matrix.front().size(); i++)
        {
            result[i] = i_matrix[row][column];

            if(direction == 0)
            {
                column++;
                if(column == rightBorder) 
                {
                    direction = (direction + 1) % 4;
                    rightBorder--;
                }
            }
            else if(direction == 1)
            {
                row++;
                if(row == downBorder) 
                {
                    direction = (direction + 1) % 4;
                    downBorder--;
                }
            }
            else if(direction == 2)
            {
                column--;
                if(column == leftBorder) 
                {
                    direction = (direction + 1) % 4;
                    leftBorder++;
                }
            }
            else if(direction == 3)
            {
                row--;
                if(row == upBorder) 
                {
                    direction = (direction + 1) % 4;
                    upBorder++;
                }
            }
        }

        return result;
    }
};
Last updated:
Tags: 数组
comments powered by Disqus