Rust 力扣 - 59. 螺旋矩阵 II

文章目录

题目描述

题解思路

使用一个全局变量current记录当前遍历到的元素的值

我们只需要一圈一圈的从外向内遍历矩阵,每一圈遍历顺序为上边、右边、下边、左边,每遍历完一个元素后current++

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

题解代码

rust 复制代码
impl Solution {
    pub fn generate_matrix(n: i32) -> Vec<Vec<i32>> {
        let mut ans = vec![vec![0; n as usize]; n as usize];

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

        let mut current = 1;

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

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

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

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

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

        ans
    }
}

题目链接

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

相关推荐
涡能增压发动积7 小时前
同样的代码循环 10次正常 循环 100次就抛异常?自定义 Comparator 的 bug 让我丢尽颜面
后端
Wenweno0o7 小时前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
小O的算法实验室7 小时前
2026年ASOC,基于深度强化学习的无人机三维复杂环境分层自适应导航规划方法,深度解析+性能实测
算法·无人机·论文复现·智能算法·智能算法改进
swg3213217 小时前
Spring Boot 3.X Oauth2 认证服务与资源服务
java·spring boot·后端
tyung7 小时前
一个 main.go 搞定协作白板:你画一笔,全世界都看见
后端·go
gelald7 小时前
SpringBoot - 自动配置原理
java·spring boot·后端
chenjingming6668 小时前
jmeter线程组设置以及串行和并行设置
java·开发语言·jmeter
cch89188 小时前
Python主流框架全解析
开发语言·python
不爱吃炸鸡柳8 小时前
C++ STL list 超详细解析:从接口使用到模拟实现
开发语言·c++·list
十五年专注C++开发8 小时前
RTTR: 一款MIT 协议开源的 C++ 运行时反射库
开发语言·c++·反射