--- title: '54. Spiral Matrix' description: Given an m x n matrix, return all elements of the matrix in spiral order icon: dot topics: - { name: "Array", slug: "array" } - { name: "Matrix", slug: "matrix" } - { name: "Simulation", slug: "simulation" } video: "BJnMZNwUk1M" issue: "https://github.com/prdlk/leetcode/issues/92" companies: - { name: "Bloomberg", period: "Thirty Days", frequency: 69.8 } - { name: "Microsoft", period: "Thirty Days", frequency: 57.2 } - { name: "Google", period: "Thirty Days", frequency: 36.7 } - { name: "Amazon", period: "Three Months", frequency: 46 } - { name: "Meta", period: "Three Months", frequency: 34.5 } - { name: "Capital One", period: "Six Months", frequency: 73.8 } - { name: "tcs", period: "Six Months", frequency: 69.7 } - { name: "Apple", period: "Six Months", frequency: 64.8 } - { name: "Infosys", period: "Six Months", frequency: 56.2 } - { name: "TikTok", period: "Six Months", frequency: 55.2 } sidebar: label: 'Spiral Matrix' badge: 'Medium' --- ### 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` ## Approach ```mermaid flowchart TD S(["spiralOrder(matrix)"]) --> I["res = [], top = 0, bottom = len(matrix) - 1, left = 0, right = len(matrix[0]) - 1"] I --> W{"top <= bottom and left <= right?"} W -- no --> E(["return res"]) W -- yes --> T["append matrix[top][c] for c in left..right, then top += 1 — top row, shrink from above"] T --> R["append matrix[r][right] for r in top..bottom, then right -= 1 — right column"] R --> B{"top <= bottom?"} B -- yes --> C["append matrix[bottom][c] for c in right down to left, then bottom -= 1 — bottom row"] C --> L{"left <= right?"} B -- no --> L L -- yes --> D["append matrix[r][left] for r in bottom down to top, then left += 1 — left column"] D --> W L -- no --> W ``` ## Solution ```py class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: res = [] top, bottom = 0, len(matrix) - 1 left, right = 0, len(matrix[0]) - 1 while top <= bottom and left <= right: # 1. Top Row for c in range(left, right + 1): res.append(matrix[top][c]) top += 1 # 2. Right Column for r in range(top, bottom + 1): res.append(matrix[r][right]) right -= 1 # 3. Bottom Row if top <= bottom: for c in range(right, left - 1, -1): res.append(matrix[bottom][c]) bottom -= 1 # 4. Left Column if left <= right: for r in range(bottom, top - 1, -1): res.append(matrix[r][left]) left += 1 return res ```