Print Matrix in Spiral Manner - Optimal Solution

Print Matrix in Spiral Manner - Optimal Solution

Algorithm Steps

  1. Given a 2D matrix of size m x n.
  2. Initialize four variables: top = 0, bottom = m - 1, left = 0, right = n - 1.
  3. Traverse the matrix in a spiral form while top <= bottom and left <= right:
  4. → Traverse from left to right across the top row and increment top.
  5. → Traverse from top to bottom along the right column and decrement right.
  6. → If top <= bottom, traverse from right to left across the bottom row and decrement bottom.
  7. → If left <= right, traverse from bottom to top along the left column and increment left.
  8. Repeat until all elements are printed.

Print Matrix Elements in Spiral Order Code

Python
JavaScript
Java
C++
C
def spiral_order(matrix):
    result = []
    if not matrix:
        return result

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

    while top <= bottom and left <= right:
        for i in range(left, right + 1):
            result.append(matrix[top][i])
        top += 1

        for i in range(top, bottom + 1):
            result.append(matrix[i][right])
        right -= 1

        if top <= bottom:
            for i in range(right, left - 1, -1):
                result.append(matrix[bottom][i])
            bottom -= 1

        if left <= right:
            for i in range(bottom, top - 1, -1):
                result.append(matrix[i][left])
            left += 1

    return result

# Sample Input
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Spiral Order:", spiral_order(matrix))