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/

相关推荐
AlbertLuo13 小时前
CodeMirror使用: 编写一个在线编辑HTML、JS、CSS文件,网页的模板页面-初实现
后端
SamDeepThinking13 小时前
裁掉那个差程序员后,给你看团队里高手的代码:这个习惯,希望你有
java·后端·程序员
花褪残红青杏小13 小时前
Rust图像处理第9节-Sobel 边缘检测:第一个真正用卷积的算法
rust·webassembly·图形学
vivo互联网技术13 小时前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
Oneslide14 小时前
windows 11远程桌面连Ubuntu GNOME 远程登录频繁断开
后端
咕白m62514 小时前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
浮生望15 小时前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
云技纵横15 小时前
@Transactional 里套 REQUIRES_NEW,为什么会把连接池耗尽?
后端·面试
tcdos15 小时前
不止扫码 — 微信生态深度融合(登录 + 支付 + 消息)
后端·微信小程序