150强访谈简单

旋转图像

“旋转图像”问题的详细指南和 Python 实现。

问题陈述

简单

给定一个代表图像的 n x n 2D 矩阵,将图像旋转 90 度(顺时针)。

您必须就地旋转图像,这意味着您必须直接修改输入的二维矩阵。不要分配另一个二维矩阵并进行旋转。

实现一个函数 rotate(matrix: list) -> list ,它可以就地旋转矩阵并返回它。

约束条件
  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

示例

Example 1
Input
[[1,2,3],[4,5,6],[7,8,9]]
Output
[[7,4,1],[8,5,2],[9,6,3]]
Explanation

The matrix is rotated 90 degrees clockwise. The first column [1,4,7] becomes the first row [7,4,1] reversed.

Example 2
Input
[[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output
[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Explanation

Each layer of the 4x4 matrix is rotated 90 degrees clockwise.

Need a Hint?
考虑使用数学和几何特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。