Spiral Order Matrix Printing | Step-by-Step Guide with Code

Spiral Order Matrix Printing | Step-by-Step Guide with Code

Spiral Order Matrix Printing | Step-by-Step Guide with Code

Printing a 2D matrix in spiral form is a popular interview problem that involves traversing the elements in a specific order. This article explains the problem, its solution, and a Python implementation. We’ll also provide test cases, algorithm breakdowns, and tips to understand and visualize this problem better.


Problem Statement

Given a matrix of size M×NM \times N, print its elements in spiral order. The traversal begins from the top-left corner and moves as follows:

  1. Left to right across the top row.
  2. Top to bottom down the rightmost column.
  3. Right to left across the bottom row.
  4. Bottom to top up the leftmost column.

Example Test Case

Input:

Matrix:

[123456789101112131415161718]\begin{bmatrix} 1 & 2 & 3 & 4 & 5 & 6 \\ 7 & 8 & 9 & 10 & 11 & 12 \\ 13 & 14 & 15 & 16 & 17 & 18 \end{bmatrix}

Output:
1,2,3,4,5,6,12,18,17,16,15,14,13,7,8,9,10,111, 2, 3, 4, 5, 6, 12, 18, 17, 16, 15, 14, 13, 7, 8, 9, 10, 11


Algorithm to Print Matrix in Spiral Form

  1. Initialize Boundaries: Define the boundaries of the matrix: top, bottom, left, and right.
  2. Traverse Layers:
    • Traverse from left to right across the top boundary.
    • Traverse from top to bottom along the right boundary.
    • Traverse from right to left across the bottom boundary.
    • Traverse from bottom to top along the left boundary.
  3. Update Boundaries: After each traversal, adjust the boundaries to exclude the traversed layer.
  4. Stop Condition: Repeat the steps until all elements are traversed.

Python Implementation

python
def spiral_order(matrix):
"""
Print the elements of a 2D array in spiral order.
Args:
matrix (list of list of int): Input 2D matrix.
Returns:
list: List of elements in spiral order.
"""

if not matrix or not matrix[0]:
return []

top, bottom = 0, len(matrix) – 1
left, right = 0, len(matrix[0]) – 1
result = []

while top <= bottom and left <= right:
# Traverse from left to right across the top row
for i in range(left, right + 1):
result.append(matrix[top][i])
top += 1

# Traverse from top to bottom along the right column
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1

# Traverse from right to left across the bottom row
if top <= bottom:
for i in range(right, left – 1, –1):
result.append(matrix[bottom][i])
bottom -= 1

# Traverse from bottom to top along the left column
if left <= right:
for i in range(bottom, top – 1, –1):
result.append(matrix[i][left])
left += 1

return result

# Example Test Cases
matrix = [
[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18]
]
print(spiral_order(matrix)) # Output: [1, 2, 3, 4, 5, 6, 12, 18, 17, 16, 15, 14, 13, 7, 8, 9, 10, 11]


Time Complexity

  • O(M * N): Each element is visited exactly once.