每日一题——螺旋矩阵

2023-08-19  本文已影响0人  拉普拉斯妖kk

题目


给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。

数据范围:0≤n,m≤10,矩阵中任意元素都满足 ∣val∣≤100

要求:空间复杂度 O(nm) ,时间复杂度 O(nm)

示例1

输入:
[[1,2,3],[4,5,6],[7,8,9]]
返回值:
[1,2,3,6,9,8,7,4,5]

示例2

输入:
[]
返回值:
[]

思路


解答代码


#include <vector>
class Solution {
public:
    /**
     * @param matrix int整型vector<vector<>> 
     * @return int整型vector
     */
    vector<int> spiralOrder(vector<vector<int> >& matrix) {
        // write code here
        auto row_size = matrix.size();
        if (row_size == 0) {
            return vector<int>{};
        }
        auto col_size = matrix[0].size();
        // 上边界
        int top = 0;
        // 下边界
        int bottom = row_size - 1;
        // 左边界
        int left = 0;
        // 右边界
        int right = col_size - 1;
        vector<int> res;
        while (top <= bottom && left <= right) {
            // 从左到右遍历上边界
            for (int i = left; i <= right; i++) {
                res.push_back(matrix[top][i]);
            }
            // 上边界下移
            ++top;
            if (top > bottom)
                break;
            // 从上到下遍历右边界
            for (int i = top; i <= bottom; i++) {
                res.push_back(matrix[i][right]);
            }
            // 左移右边界
            --right;
            if (right < left)
                break;
            // 从右到左遍历下边界
            for (int i = right; i >=left; i--) {
                res.push_back(matrix[bottom][i]);
            }
            // 上移下边界
            --bottom;
            if (bottom < top)
                break;
            // 从下到上遍历左边界
            for (int i = bottom; i >= top; i--) {
                res.push_back(matrix[i][left]);
            }
            // 右移左边界
            ++left;
            if (left > right)
                break;
        }
        return res;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读