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/

相关推荐
OPEN-F2 小时前
C++进阶教程:继承与多态
开发语言·c++
Sherotree3 小时前
Google Antigravity——Agent 被提到主界面
前端·ide·后端·edge浏览器
鹿角片ljp3 小时前
LeetCode 236. 二叉树的最近公共祖先|递归后序
算法
2601_962056234 小时前
Spring Boot 入门 与 无法解析符号 springframework 的解决
java·spring boot·后端
luj_17684 小时前
大律师考核应重能力与科技素养
c语言·开发语言·c++·经验分享·算法
无定义_4 小时前
Floyd——Warshall
算法
刃神太酷啦4 小时前
Linux 系统 MySQL 完整安装配置教程:从卸载 MariaDB 到优化 my.cnf----《Hello MySQL!》(1)
android·linux·c语言·c++·mysql·leetcode·mariadb
你驴我4 小时前
WhatsApp 多账号场景下的会话归档与历史消息检索优化实践
后端·python
学长毕业设计5 小时前
基于SpringBoot的瑜伽馆网站的设计与实现(源码+文档+讲解视频)
java·spring boot·后端
带多刺的玫瑰5 小时前
Leecode#9刷题之回文数
数据结构·算法