LeetCode 59. 螺旋矩阵 II

LeetCode 59. 螺旋矩阵 II

题目描述

给定正整数 n,构造一个 n×n 的方阵,按顺时针螺旋顺序填入 1 的所有整数。

示例

输入:3

输出:

复制代码
[
 [1, 2, 3],
 [8, 9, 4],
 [7, 6, 5]
]

解题思路

模拟顺时针填充过程,通过维护四条边界逐步收缩:

  1. 初始化 :创建 n×n 矩阵,设定初始边界 top=0, bottom=n-1, left=0, right=n-1
  2. 分层填充
    • 上层 :从左到右填充 top 行,完成后 top++
    • 右层 :从上到下填充 right 列,完成后 right--
    • 下层 :从右到左填充 bottom 行,完成后 bottom--
    • 左层 :从下到上填充 left 列,完成后 left++
  3. 终止条件 :当填充数字超过 时结束

代码实现

java 复制代码
class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int num = 1, max = n * n;
        int top = 0, bottom = n - 1, left = 0, right = n - 1;
        
        while (num <= max) {
            // 上层:从左到右
            for (int i = left; i <= right; i++) matrix[top][i] = num++;
            top++;
            
            // 右层:从上到下
            for (int i = top; i <= bottom; i++) matrix[i][right] = num++;
            right--;
            
            // 下层:从右到左
            for (int i = right; i >= left; i--) matrix[bottom][i] = num++;
            bottom--;
            
            // 左层:从下到上
            for (int i = bottom; i >= top; i--) matrix[i][left] = num++;
            left++;
        }
        return matrix;
    }
}

复杂度分析

  • 时间复杂度:O(n²) --- 每个元素被访问一次
  • 空间复杂度:O(n²) --- 存储结果矩阵
相关推荐
MIUMIUKK1 天前
双指针三大例题
算法
灵感__idea1 天前
Hello 算法:复杂问题的应对策略
前端·javascript·算法
2301_819414301 天前
C++与区块链智能合约
开发语言·c++·算法
Zaly.1 天前
【Python刷题】LeetCode 1727 重新排列后的最大子矩阵
算法·leetcode·矩阵
做怪小疯子1 天前
蚂蚁暑期 319 笔试
算法·职场和发展
计算机安禾1 天前
【C语言程序设计】第37篇:链表数据结构(一):单向链表的实现
c语言·开发语言·数据结构·c++·算法·链表·蓝桥杯
啊哦呃咦唔鱼1 天前
LeetCode hot100-73 矩阵置零
算法
阿贵---1 天前
C++构建缓存加速
开发语言·c++·算法
Queenie_Charlie1 天前
最长回文子串 V2(Manacher算法)
c++·算法·manacher算法
Evand J1 天前
【MATLAB复现RRT(快速随机树)算法】用于二维平面上的无人车路径规划与避障,含性能分析与可视化
算法·matlab·平面·无人车·rrt·避障