LeetCode 题解工作台
螺旋矩阵
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。 示例 1: 输入: matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出: [1,2,3,6,9,8,7,4,5] 示例 2: 输入: matrix = [[1,2,3,4],[5…
3
题型
8
代码语言
3
相关题
当前训练重点
中等 · 数组·matrix
答案摘要
我们可以模拟整个遍历的过程,用 和 分别表示当前访问到的元素的行和列,用 表示当前的方向,用数组或哈希表 记录每个元素是否被访问过。每次我们访问到一个元素后,将其标记为已访问,然后按照当前的方向前进一步,如果前进一步后发现越界或者已经访问过,则改变方向继续前进,直到遍历完整个矩阵。 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 和 分别是…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路
题目描述
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100
解题思路
方法一:模拟
我们可以模拟整个遍历的过程,用 和 分别表示当前访问到的元素的行和列,用 表示当前的方向,用数组或哈希表 记录每个元素是否被访问过。每次我们访问到一个元素后,将其标记为已访问,然后按照当前的方向前进一步,如果前进一步后发现越界或者已经访问过,则改变方向继续前进,直到遍历完整个矩阵。
时间复杂度 ,空间复杂度 。其中 和 分别是矩阵的行数和列数。
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
dirs = (0, 1, 0, -1, 0)
vis = [[False] * n for _ in range(m)]
i = j = k = 0
ans = []
for _ in range(m * n):
ans.append(matrix[i][j])
vis[i][j] = True
x, y = i + dirs[k], j + dirs[k + 1]
if x < 0 or x >= m or y < 0 or y >= n or vis[x][y]:
k = (k + 1) % 4
i += dirs[k]
j += dirs[k + 1]
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the number of elements in the matrix, which is O(m _n). Space complexity is O(1) if the solution modifies the matrix in-place, but it could be O(m_ n) if a new array is created to store the result. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you understand the process of adjusting boundaries dynamically in a spiral traversal?
- question_mark
Can you explain how the simulation approach helps to cover all matrix elements in spiral order?
- question_mark
Will you be able to handle edge cases such as 1x1 matrices or matrices with only one row or column?
常见陷阱
外企场景- error
Not adjusting the boundaries after each pass (top, bottom, left, right) will cause revisiting the same elements.
- error
Forgetting to handle matrices with only one row or column could result in out-of-bound errors or incorrect results.
- error
Overcomplicating the solution by using unnecessary data structures instead of simulating the traversal directly.
进阶变体
外企场景- arrow_right_alt
Spiral matrix traversal with specific steps removed (e.g., no rightward movement allowed).
- arrow_right_alt
Spiral traversal of an n x n matrix where elements are updated instead of just being read.
- arrow_right_alt
Return the matrix elements in reverse spiral order.