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/

相关推荐
Dxy12393102165 小时前
Python 使用正则表达式将多个空格替换为一个空格
开发语言·python·正则表达式
我学上瘾了5 小时前
Spring Cloud的前世今生
后端·spring·spring cloud
波波0076 小时前
ASP.NET Core 健康检查实战:不只是一个 /health 接口
后端·asp.net
小码哥_常6 小时前
Spring Boot 搭建邮件发送系统:开启你的邮件自动化之旅
后端
故事和你917 小时前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
脱氧核糖核酸__7 小时前
LeetCode热题100——53.最大子数组和(题解+答案+要点)
数据结构·c++·算法·leetcode
脱氧核糖核酸__7 小时前
LeetCode 热题100——42.接雨水(题目+题解+答案)
数据结构·c++·算法·leetcode
石榴树下的七彩鱼7 小时前
图片修复 API 接入实战:网站如何自动去除图片水印(Python / PHP / C# 示例)
图像处理·后端·python·c#·php·api·图片去水印
我叫黑大帅7 小时前
为什么TCP是三次握手?
后端·网络协议·面试
我叫黑大帅8 小时前
如何排查 MySQL 慢查询
后端·sql·面试