面试题 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;
    }
};
相关推荐
月明长歌4 分钟前
【码道初阶】【LeetCode 160】相交链表:让跑者“起跑线对齐”的智慧
java·算法·leetcode·链表
beordie.cloud9 分钟前
LeetCode 49. 字母异位词分组 | 从排序到计数的哈希表优化之路
算法·leetcode·散列表
共享家952714 分钟前
每日一题(一)
算法
fufu031118 分钟前
Linux环境下的C语言编程(四十一)
linux·c语言·算法
bing.shao24 分钟前
Golang 之闭包
java·算法·golang
顾子羡_Gu24 分钟前
算法进阶指南:搜索与数论基础
数据结构·算法
2301_7737303127 分钟前
数据结构—队列
数据结构
唯道行43 分钟前
计算机图形学·25 消隐2 区域子分算法-光线投射算法
人工智能·算法·计算机视觉·计算机图形学·opengl
jinxinyuuuus1 小时前
FIRE之旅 财务计算器:实时交互式建模与前端性能工程
前端·人工智能·算法·自动化
千丈之松1 小时前
能力和法律
算法