Menu Close

Return all elements of the matrix in spiral order

Given an m x n matrix, return all elements of the matrix in spiral order.

Input: 
matrix = [[1,2,3],[4,5,6],[7,8,9]]

Output: [1,2,3,6,9,8,7,4,5]
def printSpiralOrder(mat):
    # base case
    if not mat or not len(mat):
        return
    top = left = 0
    bottom = len(mat) - 1
    right = len(mat[0]) - 1

    while True:
        if left > right:
            break
        # print top row
        for i in range(left, right + 1):
            print(mat[top][i], end=' ')
        top = top + 1

        if top > bottom:
            break
        # print right column
        for i in range(top, bottom + 1):
            print(mat[i][right], end=' ')
        right = right - 1

        if left > right:
            break
        # print bottom row
        for i in range(right, left - 1, -1):
            print(mat[bottom][i], end=' ')
        bottom = bottom - 1

        if top > bottom:
            break
        # print left column
        for i in range(bottom, top - 1, -1):
            print(mat[i][left], end=' ')
        left = left + 1


#Driver
Matrx = []
'''
Matrx = [
        [1, 2, 3, 4, 5],
        [16, 17, 18, 19, 6],
        [15, 24, 25, 20, 7],
        [14, 23, 22, 21, 8],
        [13, 12, 11, 10, 9]
    ]
'''
while True:
    arr=list(map(str,input().split(" ")))
    if arr != ['']:
        Matrx.append(list(map(int,arr)))
    else:
        break
printSpiralOrder(Matrx)

INPUT_1:
1  2  3  4  5
16  17  18  19  6
15  24  25  20  7
14  23  22  21  8
13  12  11  10  9

OUTPUT:
1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25


INPUT_2:
100  200  300
400  500  600
700  800  900

OUTPUT:
100  200  300  600  900  800  700  400  500


INPUT_3:
5  6  7
10  9  8

OUTPUT:
5  6  7  8  9  10


ILLUSTRATION

Executed using python3 linux terminal

Morae Q!