面试题 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;
    }
};
相关推荐
菜菜的顾清寒2 分钟前
力扣HOT100(41)动态规划-杨辉三角
算法·leetcode·动态规划
Cthy_hy7 分钟前
Python算法竞赛:集合去重+字典映射 核心用法一站式整理
数据结构·python·算法
Deepoch14 分钟前
Deepoc数学大模型:驱动发动机行业数智化转型的底层解
人工智能·算法·deepoc·数学大模型
happymaker062616 分钟前
LeetCodeHot100——盛水最多的容器
数据结构·算法·leetcode·双指针·hot100
3DVisionary17 分钟前
蓝光三维扫描:磁性轴承全尺寸精密3D检测方案
算法·3d·3d检测·蓝光三维扫描·精密检测·磁性轴承·圆度测量
过期动态23 分钟前
【LeetCode 热题 100】三数之和
java·数据结构·算法·leetcode·职场和发展·排序算法
逻辑君27 分钟前
Foresight研究报告【20260010】
人工智能·算法·机器学习
一切皆是因缘际会29 分钟前
AI高速迭代下的技术风险与理性突围
大数据·数据结构·人工智能·架构
weixin_4684668531 分钟前
大语言模型原理新手入门指南
人工智能·python·算法·语言模型·自然语言处理·transformer·注意力机制
z2005093035 分钟前
今日算法(回溯找IP,加检测)
算法·leetcode