Spiral Matrix 解題教學:3 種解法完整比較|LeetCode 54 Best Practice

Spiral Matrix 解題教學示意圖|LeetCode 54

本文完整拆解 LeetCode 54 Spiral Matrix 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Spiral Matrix 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link

Given an m x n matrix, return all elements of the matrix in spiral order.

 

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

 

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100
				
					# time complexity: O(m*n)
# space complexity: O(1)
from typing import List


class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        ROW = len(matrix)
        COL = len(matrix[0])
        direction = 1
        row = 0
        col = -1
        result = []
        while ROW > 0 and COL > 0:
            for _ in range(COL):
                col += direction
                result.append(matrix[row][col])
            ROW -= 1
            for _ in range(ROW):
                row += direction
                result.append(matrix[row][col])
            COL -= 1

            direction *= -1

        return result


matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(Solution().spiralOrder(matrix))
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
print(Solution().spiralOrder(matrix))
				
			

Spiral Matrix 解題思路

螺旋走訪的本質是「四個邊界不斷向內收縮」。與其用方向向量加上訪問標記,不如直接維護 top、bottom、left、right 四個邊界:每走完一條邊就把對應的邊界往內推一格,當邊界交錯時就結束。這樣完全不需要額外的 visited 陣列。

Spiral Matrix 演算法步驟

  1. 初始化 top=0、bottom=m-1、left=0、right=n-1。
  2. 由左到右走 top 這一列,然後 top++。
  3. 由上到下走 right 這一行,然後 right–;若 top <= bottom 則由右到左走 bottom 列並 bottom--。
  4. 若 left <= right 則由下到上走 left 行並 left++,重複直到邊界交錯。

Spiral Matrix 複雜度分析

項目複雜度
時間複雜度O(m·n)
空間複雜度O(1)

每個元素恰好被輸出一次,時間為 O(m·n),這是下界。只用四個邊界變數,額外空間為 O(1)(不計輸出陣列)。

Spiral Matrix 的邊界情況與常見錯誤

  • 非方陣時,走完上下兩列後必須檢查 top <= bottom 才能走回頭,否則會重複輸出。
  • 單列或單行的矩陣是最容易出錯的測資,一定要測。
  • 空矩陣要直接回傳空陣列。
  • 邊界更新的順序不能顛倒,否則會少走或多走一格。

Spiral Matrix 其他解法比較

解法時間空間說明
方向向量 + visited 陣列O(m·n)O(m·n)好懂但多花一個矩陣的空間
遞迴剝洋蔥O(m·n)O(min(m,n))寫法優雅但有堆疊成本
四邊界收縮O(m·n)O(1)本文採用