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/

相关推荐
灵感__idea5 小时前
Hello 算法:贪心的世界
前端·javascript·算法
小成202303202656 小时前
Linux高级02
linux·开发语言
知行合一。。。6 小时前
Python--04--数据容器(总结)
开发语言·python
咸鱼2.06 小时前
【java入门到放弃】需要背诵
java·开发语言
ZK_H6 小时前
嵌入式c语言——关键字其6
c语言·开发语言·计算机网络·面试·职场和发展
澈2076 小时前
深入浅出C++滑动窗口算法:原理、实现与实战应用详解
数据结构·c++·算法
A.A呐6 小时前
【C++第二十九章】IO流
开发语言·c++
椰猫子6 小时前
Java:异常(exception)
java·开发语言
lifewange6 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
GreenTea6 小时前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端