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/

相关推荐
高频因子挖掘机39 分钟前
同一交易日出现重复 K 线:去重前先确认时间、来源和粒度
后端·github·api
feely02082 小时前
《我写了 31 个静态扫描插件,踩了 7 个「假绿」》
后端
橙子家2 小时前
参数校验类异常(Argument Exception)【C# Exception 详解系列一】
后端
掘金挖土3 小时前
前端手摸手跑路之 AI 应用开发(九)
前端·后端
全栈弄潮儿3 小时前
Python实战第8期:函数
后端·python·编程语言
码事漫谈3 小时前
你让 AI “尽力做”,它反而可能做不好
后端
孟健4 小时前
LLM API 安全防线:从 OpenCode 盗刷事件到 LiteLLM 多模型容灾实操
人工智能·后端·架构
程序员cxuan4 小时前
我用 WorkBuddy + ima 把公众号文章做成了知识库。
人工智能·后端·程序员
程序员cxuan5 小时前
玩了一天 REA,我号快没了
人工智能·后端·程序员