LeetCode54. 螺旋矩阵(2024秋季每日一题 21)

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 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

提示:

m = = m a t r i x . l e n g t h m == matrix.length m==matrix.length
n = = m a t r i x i . l e n g t h n == matrixi.length n==matrixi.length
1 < = m , n < = 10 1 <= m, n <= 10 1<=m,n<=10
− 100 < = m a t r i x i j < = 100 -100 <= matrixij <= 100 −100<=matrixij<=100


思路:

    1. 将 右、下、左、上 分别映射为 0~3 个方向
    1. 刚开始从 (0, 0) 坐标位置开始出发,从 0 方向(右方向)开始走
    1. 当此时的 坐标越界,或者已经访问过元素,开始转换方向 (t + 1) % 4
    1. 直到遍历的元素等于原数组元素的 个数,则返回
cpp 复制代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int n = matrix.size(), m = matrix[0].size();
        bool st[n][m];
        memset(st, 0, sizeof st);
        int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
        int t = 0, cnt = n * m;
        vector<int> res;
        int x = 0, y = 0;
        st[0][0] = true;
        res.push_back(matrix[0][0]);
        while(res.size() != cnt){
            int a = x + dx[t], b = y + dy[t];
            if(a < 0 || a >= n || b < 0 || b >= m || st[a][b]){
                t = (t + 1) % 4;
                continue;
            }
            x = a, y = b;
            st[a][b] = true;
            res.push_back(matrix[x][y]);
        }
        return res;
    }
};
相关推荐
AI科技星39 分钟前
特征值与特征向量不是矩阵特殊解,是变换矩阵下不改变生长方向、仅缩放体量的固有主螺旋脉络 -《全域数学vs传统数学:人类文明进阶200讲》第73讲
人工智能·线性代数·矩阵·数据挖掘·回归·乖乖数学·全域数学
学究天人2 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷7)
线性代数·矩阵·动态规划·概率论·图论·抽象代数·拓扑学
学究天人4 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷8)
线性代数·算法·机器学习·数学建模·动态规划·图论·抽象代数
USB_ABC6 小时前
视频矩阵核心技术对比:模块化vs固定机箱、硬件帧同步vs软件同步怎么选
矩阵·音视频
workflower1 天前
室内外配送机器人-应用路径
人工智能·机器学习·设计模式·矩阵·自动化
hai3152475431 天前
九章编译法----空间几何统一编译法
网络·汇编·人工智能·线性代数
玛卡巴卡ldf1 天前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
lin9902121 天前
内容矩阵批量分发实战
大数据·人工智能·矩阵
学究天人1 天前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷3.2)
线性代数·算法·机器学习·数学建模·动态规划·抽象代数·拓扑学
学究天人1 天前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷1)
线性代数·机器学习·数学建模·动态规划·图论·抽象代数·傅立叶分析