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/

相关推荐
语落心生几秒前
Apache Geaflow推理框架Geaflow-infer 解析系列(五)环境上下文管理
后端
程序员爱钓鱼2 分钟前
用 Python 批量生成炫酷扫光 GIF 动效
后端·python·trae
封奚泽优5 分钟前
下降算法(Python实现)
开发语言·python·算法
im_AMBER12 分钟前
算法笔记 16 二分搜索算法
c++·笔记·学习·算法
高洁0114 分钟前
【无标具身智能-多任务与元学习】
神经网络·算法·aigc·transformer·知识图谱
aiopencode16 分钟前
iOS 应用上架的工程实践复盘,从构建交付到审核通过的全流程拆解
后端
leoufung19 分钟前
逆波兰表达式 LeetCode 题解及相关思路笔记
linux·笔记·leetcode
笃行客从不躺平27 分钟前
遇到大SQL怎么处理
java·开发语言·数据库·sql
郝学胜-神的一滴27 分钟前
Python中常见的内置类型
开发语言·python·程序人生·个人开发
q***876034 分钟前
Spring Boot 整合 Keycloak
java·spring boot·后端