Skip to main content

Leetcode 54: Spiral Matrix

 

1. Problem Statement (Simple Explanation):


You’re given an m x n matrix.

You must return all elements in spiral order, starting from the top-left corner and spiraling:

  • Right → down → left → up → and so on, layer by layer.


2. Examples:


Example 1:


Input:

matrix = [

  [1,2,3],

  [4,5,6],

  [7,8,9]

]

Spiral order:

1 → 2 → 3 → 6 → 9 → 8 → 7 → 4 → 5

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]

]

Spiral order:

1 → 2 → 3 → 4 → 8 → 12 → 11 → 10 → 9 → 5 → 6 → 7

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


3. Approach – Boundary Tracking (Layer by Layer):


We can simulate walking around the matrix in layers, maintaining four boundaries:

  • top – index of current top row not yet traversed.

  • bottom – index of current bottom row not yet traversed.

  • left – index of current left column not yet traversed.

  • right – index of current right column not yet traversed.


Process in this order while top <= bottom and left <= right:

  1. Traverse top row from left to right. Then top++.

  2. Traverse right column from top to bottom. Then right--.

  3. If top <= bottom:

    • Traverse bottom row from right to left. Then bottom--.

  4. If left <= right:

    • Traverse left column from bottom to top. Then left++.

Repeat until boundaries cross.


Pseudo-code:



Complexity:


Let m = rows, n = columns:

  • Time: We visit each element once → O(m⋅n).

  • Space: O(1) extra (excluding the output list).


4. Java code:



5. C
code:



6. C++
code:



7. Python code:



8. JavaScript code:


Comments