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/

相关推荐
changhong19863 小时前
如何在 Spring Boot 中配置数据库?
数据库·spring boot·后端
Filotimo_3 小时前
5.3 Internet基础知识
开发语言·php
识君啊3 小时前
Java异常处理:中小厂面试通关指南
java·开发语言·面试·异常处理·exception·中小厂
qyzm5 小时前
天梯赛练习(3月13日)
开发语言·数据结构·python·算法·贪心算法
月月玩代码5 小时前
Actuator,Spring Boot应用监控与管理端点!
java·spring boot·后端
逆境不可逃5 小时前
LeetCode 热题 100 之 64. 最小路径和 5. 最长回文子串 1143. 最长公共子序列 72. 编辑距离
算法·leetcode·动态规划
leluckys5 小时前
swift- Swift中常见的面试题
开发语言·汇编·swift
BUG_MeDe5 小时前
json格式字符串解析的简单使用 libjson-c
c语言·开发语言·json
XPoet6 小时前
AI 编程工程化:Skill——给你的 AI 员工装上技能包
前端·后端·ai编程
CoderCodingNo6 小时前
【GESP】C++五级练习题 luogu-P1182 数列分段 Section II
开发语言·c++·算法