Rust 力扣 - 54. 螺旋矩阵

文章目录

题目描述

题解思路

我们只需要一圈一圈的从外向内遍历矩阵,每一圈遍历顺序为上边、右边、下边、左边

我们需要注意的是如果上边与下边重合或者是右边与左边重合,我们只需要遍历上边、右边即可

题解代码

rust 复制代码
impl Solution {
    pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
        let (m, n) = (matrix.len(), matrix[0].len());

        let mut ans = Vec::with_capacity(m * n);

        let (mut t, mut b, mut l, mut r) = (0, m - 1, 0, n - 1);

		// 从外圈向内圈遍历
        while l <= r && t <= b {
            // 上边 从左到右
            for i in l..=r {
                ans.push(matrix[t][i]);
            }

            // 右边 从上到下
            for i in (t + 1)..=b {
                ans.push(matrix[i][r]);
            }

            if l < r && t < b {
                // 下边 从右到左
                for i in ((l + 1)..r).rev() {
                    ans.push(matrix[b][i]);
                }

                // 左边 从下到上
                for i in ((t + 1)..=b).rev() {
                    ans.push(matrix[i][l]);
                }
            }

            l += 1;
            if r != 0 {
                r -= 1;
            }
            t += 1;
            if b != 0 {
                b -= 1;
            }
        }

        ans
    }
}

题目链接

https://leetcode.cn/problems/spiral-matrix/

相关推荐
为思念酝酿的痛3 小时前
POSIX信号量
linux·运维·服务器·后端
小羊在睡觉3 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
3DVisionary3 小时前
蓝光三维扫描:医疗制造的精度焦虑怎么解
人工智能·算法·制造·蓝光三维扫描·医疗制造·三维检测·义齿检测
AI玫瑰助手3 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
jiayong233 小时前
面试中遇到不熟悉问题的应对策略深度解析
面试·职场和发展
好评笔记3 小时前
机器学习面试八股——常用损失函数
人工智能·深度学习·算法·机器学习·校招
weixin_468466853 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
油炸自行车3 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋3 小时前
C++14特性
开发语言·c++·c++14特性
sheeta19984 小时前
LeetCode 每日一题笔记 日期:2026.05.29 题目:3300. 最小元素
笔记·leetcode