面试题 29. 顺时针打印矩阵

顺时针打印矩阵

题目描述

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

示例

示例 1:

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

输出:1,2,3,6,9,8,7,4,5

题解

从外往里一圈一圈遍历并存储矩阵元素即可。

cpp 复制代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int rows = matrix.size(), cols = matrix[0].size();
        if (rows == 0 || cols == 0) return {};

        vector<int> res;
        int top = 0, bottom = rows -1, left = 0, right = cols - 1;
        while (top <= bottom && left <= right) {
            for (int i = left; i <= right; i++) res.push_back(matrix[top][i]);
            for (int i = top + 1; i <= bottom; i++) res.push_back(matrix[i][right]);
            // 判断不可少
            if (left < right && top < bottom) {
                for (int i = right - 1; i >= left; i--) res.push_back(matrix[bottom][i]);
                // 可以模拟发现 不可以为 i >= top
                for (int i = bottom - 1; i > top; i--) res.push_back(matrix[i][left]);
            }
            top++;
            bottom--;
            left++;
            right--;
        }
        return res;
    }
};
相关推荐
Severus_black1 小时前
【C++初阶】list使用及相关实现,思路顺滑流畅!
c语言·数据结构·c++·stl·list
武子康2 小时前
H3-World 为何在加载 LoRA 前,先检查导入的代码?
人工智能·深度学习·算法
秋天的怀念_David3 小时前
算法一千零一夜 · 第二十八夜 注册
java·程序人生·算法
二本咕咕-机械转码3 小时前
FreeRTOS深入解析(八)IPC机制之FromISR详解
数据结构·单片机·链表
NEFU_Jyj5 小时前
贝尔数(组合数学)
算法
1-1=05 小时前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
希和20275 小时前
C语言程序设计题|有序数组插入数字冒泡排序
c语言·数据结构·算法
Pniubi6 小时前
力扣73 矩阵置零
算法·leetcode·矩阵
布莱克60516 小时前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map