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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。