Algorithm-Day19-Spiral-Matrix-lc-54

🧩 Problem Description

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

Example:

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

💡 Approach: Layer-by-Layer Traversal

✨ Key Idea

We maintain four boundaries:

  • top, bottom, left, right

At each step:

  1. Traverse from left to right along top.
  2. Traverse from top + 1 to bottom along right.
  3. Traverse from right - 1 to left along bottom (only if top < bottom).
  4. Traverse from bottom - 1 to top + 1 along left (only if left < right).

After each step, we shrink the boundaries inward.


🔢 Java Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.*;

class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();

if (matrix == null || matrix.length == 0) return result;

int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;

while (top <= bottom && left <= right) {
// Traverse from left to right
for (int j = left; j <= right; j++) {
result.add(matrix[top][j]);
}
top++;

// Traverse from top to bottom
for (int i = top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
right--;

if (top <= bottom) {
// Traverse from right to left
for (int j = right; j >= left; j--) {
result.add(matrix[bottom][j]);
}
bottom--;
}

if (left <= right) {
// Traverse from bottom to top
for (int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
left++;
}
}

return result;
}
}

⏱ Time and Space Complexity

  • Time Complexity: O(m × n)
    Each cell is visited exactly once.
  • Space Complexity: O(1) extra space
    (excluding output list)

✍️ Summary

  • Boundary shrinking is a classic matrix traversal technique.
  • Spiral order appears in related problems like Spiral Matrix II (filling numbers), lc-59.
  • Make sure to check conditions carefully when shrinking boundaries to avoid duplicates.

Matrix traversal patterns (row-wise, column-wise, spiral, zigzag) are common interview topics — good to master!