LeetCode 题解工作台

螺旋矩阵 II

给你一个正整数 n ,生成一个包含 1 到 n 2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。 示例 1: 输入: n = 3 输出: [[1,2,3],[8,9,4],[7,6,5]] 示例 2: 输入: n = 1 输出: [[1]] 提示: 1

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·matrix

bolt

答案摘要

我们可以直接模拟螺旋矩阵的生成过程。 定义一个二维数组 ,用于存储螺旋矩阵。用 和 分别表示当前位置的行号和列号,用 表示当前的方向编号, 表示方向编号与方向的对应关系。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix

 

示例 1:

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

示例 2:

输入:n = 1
输出:[[1]]

 

提示:

  • 1 <= n <= 20
lightbulb

解题思路

方法一:模拟

我们可以直接模拟螺旋矩阵的生成过程。

定义一个二维数组 ans\textit{ans},用于存储螺旋矩阵。用 iijj 分别表示当前位置的行号和列号,用 kk 表示当前的方向编号,dirs\textit{dirs} 表示方向编号与方向的对应关系。

11 开始,依次填入矩阵中的每个位置。每次填入一个位置后,计算下一个位置的行号和列号,如果下一个位置不在矩阵中或者已经被填过,则改变方向,再计算下一个位置的行号和列号。

时间复杂度 O(n2)O(n^2),其中 nn 是矩阵的边长。忽略答案数组的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        ans = [[0] * n for _ in range(n)]
        dirs = (0, 1, 0, -1, 0)
        i = j = k = 0
        for v in range(1, n * n + 1):
            ans[i][j] = v
            x, y = i + dirs[k], j + dirs[k + 1]
            if x < 0 or x >= n or y < 0 or y >= n or ans[x][y]:
                k = (k + 1) % 4
            i, j = i + dirs[k], j + dirs[k + 1]
        return ans
speed

复杂度分析

指标
时间\mathcal{O}(n^2)
空间\mathcal{O}(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate demonstrates an understanding of array traversal techniques.

  • question_mark

    They can describe how to adjust matrix boundaries during traversal.

  • question_mark

    They understand how to optimize for space complexity with an in-place solution.

warning

常见陷阱

外企场景
  • error

    Forgetting to adjust the boundaries after completing a row or column, causing an infinite loop or overwriting cells.

  • error

    Not properly handling edge cases, like n = 1 or a very small matrix.

  • error

    Overcomplicating the solution by using extra space when in-place filling is possible.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Generate the matrix in reverse spiral order, starting from n² and going down to 1.

  • arrow_right_alt

    Create a matrix that is filled in a diagonal pattern from top-left to bottom-right.

  • arrow_right_alt

    Simulate the matrix traversal in a zigzag pattern, filling values in a back-and-forth manner.

help

常见问题

外企场景

螺旋矩阵 II题解:数组·matrix | LeetCode #59 中等