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/

相关推荐
8Qi86 小时前
回文子串(Palindromic Substrings)—— 题解
算法·leetcode·职场和发展·动态规划
想吃火锅10059 小时前
【leetcode】405.数字转换为十六进制数js
开发语言·javascript·ecmascript
专注VB编程开发20年9 小时前
AI 生成C# WinForm 窗体 = 目前就是垃圾
开发语言·人工智能·c#
cfm_29149 小时前
JVM GC垃圾回收初步了解
java·开发语言·jvm
~小先生~9 小时前
Python从入门到放弃(一)
开发语言·python
许彰午10 小时前
17_synchronized关键字深度解析
java·开发语言
z落落10 小时前
C# 泛型接口和泛型类+泛型约束
开发语言·c#
阿正的梦工坊10 小时前
【Rust】02-变量、不可变性与基础类型
开发语言·后端·rust
阿正的梦工坊10 小时前
【Rust】08-集合类型、字符串与迭代器入门
开发语言·rust·c#