⬅ Previous Topic
Rotate Matrix by 90 Degrees ClockwiseNext Topic ⮕
Row with Maximum Number of 1's⬅ Previous Topic
Rotate Matrix by 90 Degrees ClockwiseNext Topic ⮕
Row with Maximum Number of 1'sTopic Contents
Given a 2D matrix, your task is to print all its elements in a spiral order starting from the top-left corner and moving clockwise layer by layer.
In spiral order, you start by printing the top row, then the rightmost column, then the bottom row in reverse, and finally the leftmost column from bottom to top. This process is repeated for the inner layers until all elements are printed.
If the matrix is empty or has no elements, the output should be an empty list.
m x n
.top = 0
, bottom = m - 1
, left = 0
, right = n - 1
.top <= bottom
and left <= right
:left
to right
across the top
row and increment top
.top
to bottom
along the right
column and decrement right
.top <= bottom
, traverse from right
to left
across the bottom
row and decrement bottom
.left <= right
, traverse from bottom
to top
along the left
column and increment left
.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:
# Traverse from left to right
for i in range(left, right + 1):
result.append(matrix[top][i])
top += 1
# Traverse from top to bottom
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
if top <= bottom:
# Traverse from right to left
for i in range(right, left - 1, -1):
result.append(matrix[bottom][i])
bottom -= 1
if left <= right:
# Traverse from bottom to top
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))
⬅ Previous Topic
Rotate Matrix by 90 Degrees ClockwiseNext Topic ⮕
Row with Maximum Number of 1'sYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.