# Program to print matrix elements in spiral order in python

Suppose we have a 2D matrix mat. We have to print the matrix elements in a spiral way. At first starting from the first row (mat[0, 0]), print the whole content and then follow the last column to print, then the last row, and so on, thus it prints the elements in a spiral fashion.

So, if the input is like

 7 10 9 2 9 1 6 2 3 9 1 4 2 7 5 9 9 11

then the output will be [7, 10, 9, 1, 3, 4, 5, 11, 9, 9, 2, 9, 6, 2, 9, 2, 1, 7]

To solve this, we will follow these steps:

• d := 0
• top := 0, down := row count of matrix – 1, left := 0, right := column count of matrix - 1
• c := 0
• res := a new list
• direction := 0
• while top <= down and left <= right, do
• if direction is same as 0, then
• for i in range left to right + 1, do
• insert matrix[top, i] into res
• top := top + 1
• if direction is same as 1, then
• for i in range top to down + 1, do
• insert matrix[i, right] into res
• right := right - 1
• if direction is same as 2, then
• for i in range right to left - 1, decrease by 1, do
• insert matrix[down, i] into res
• down := down - 1
• if direction is same as 3, then
• for i in range down to top - 1, decrease by 1, do
• insert matrix[i, left] into res
• left := left + 1
• direction :=(direction + 1) mod 4
• return res

Let us see the following implementation to get better understanding:

## Example

Live Demo

class Solution:
def solve(self, matrix):
d = 0
top = 0
down = len(matrix) - 1
left = 0
right = len(matrix) - 1
c = 0
res = []
direction = 0
while top <= down and left <= right:
if direction == 0:
for i in range(left, right + 1):
res.append(matrix[top][i])
top += 1

if direction == 1:
for i in range(top, down + 1):
res.append(matrix[i][right])
right -= 1

if direction == 2:
for i in range(right, left - 1, -1):
res.append(matrix[down][i])
down -= 1

if direction == 3:
for i in range(down, top - 1, -1):
res.append(matrix[i][left])
left += 1

direction = (direction + 1) % 4
return res

ob = Solution()
matrix = [
[7, 10, 9],
[2, 9, 1],
[6, 2, 3],
[9, 1, 4],
[2, 7, 5],
[9, 9, 11]
]
print(ob.solve(matrix))

## Input

[
[7, 10, 9],
[2, 9, 1],    [6, 2, 3],
[9, 1, 4],    [2, 7, 5],
[9, 9, 11]]

## Output

[7, 10, 9, 1, 3, 4, 5, 11, 9, 9, 2, 9, 6, 2, 9, 2, 1, 7]