Ibrahim Sha
3 min readDec 17, 2020

--

This blog of explaining, how to print the given matrix in the spiral order.

Photo by Ludde Lorentz on Unsplash

Spiral order:

-> start printing the element from first point (0,0) to the center point.
-> Example:
matrix = [
[1, 2, 3,4,],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],
]
output = [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
here, starting point is 1 and center point is 10.

Spiral Traversal:

-> In this problem, traversal will go only in four directions(clock wise) step by step,

-> 1. left to right
-> 2. top to bottom
-> 3. right to left
-> 4. bottom to top

-> referring to mentioned matrix datasets, traversal will go by this way

--> [1, 2, 3, 4] # left to right
--> [8, 12, 16] # top to bottom
--> [15, 14, 13] # right to left
--> [9, 5] # bottom to top
--> [6, 7] # left to right (recursive iteration, till reaching center point)
--> [11] # top to bottom (recursive iteration, till reaching center point)
--> [10] # right to left (recursive iteration, till reaching center point)

snippets for spiral matrix

data = [
[1, 2, 3,4,],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],
]

global_str = ""



def spiral_marix(data, global_str):
"""
LR-0, TB-1, RL-2, BT-3
"""
global_str = ""
row, col = len(data), len(data[0])
top, bottom = 0, row -1
left, right = 0, col-1

dir = 0
while(top <= bottom and left<= right):
if dir == 0: # LR
for i in range(left, right+1):
global_str += str(data[top][i])
print(global_str)
dir += 1
top += 1
elif dir == 1: # TB
for i in range(top, bottom + 1):
global_str += str(data[i][right])
dir += 1
right -= 1
print(global_str)
elif dir == 2: # RL
for i in range(right, left-1, -1):
global_str += str(data[bottom][i])
dir += 1
bottom -= 1
elif dir == 3: # BT
for i in range(bottom, top-1, -1):
global_str += str(data[i][left])
dir += 1
left += 1
print(global_str)
dir = dir % 4

spiral_marix(data, global_str)

Key-points(for solving this problem)

  1. Traversal should be only in 4 directions(sequentially) and define four counters(at start),
a. top = 0b. bottom = row_lenc. left = 0d. right = col_len

2. After every traversal, update the counter value,

a. left to right direction(dir=0) -> top += 1
b. top to bottom direction(dir=1) -> right -= 1
c. right to left direction(dir=2) -> bottom -= 1
d. bottom to top direction(dir=3) -> left += 1

Note: Purpose of managing counter, is to avoid printing repeated elements

3. Reset the direction counter to 0, every-time it reaches four directions.

dir = dir % 4 

4. Keep the iterations running, until top counter value greater than bottom counter value and vice versa for right and left counter value.

while(top <= bottom and left<= right)

Reference:

  1. https://www.youtube.com/watch?v=1ZGJzvkcLsA
  2. https://www.youtube.com/watch?v=qEZoUVOqOs8

--

--