Algorithm Steps
- Given a 2D matrix of size
m x n
. - Initialize four variables:
top = 0
,bottom = m - 1
,left = 0
,right = n - 1
. - Traverse the matrix in a spiral form while
top <= bottom
andleft <= right
: - → Traverse from
left
toright
across thetop
row and incrementtop
. - → Traverse from
top
tobottom
along theright
column and decrementright
. - → If
top <= bottom
, traverse fromright
toleft
across thebottom
row and decrementbottom
. - → If
left <= right
, traverse frombottom
totop
along theleft
column and incrementleft
. - 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))