spiral print Algorithm
The spiral print algorithm is a technique used to traverse and print a 2D matrix in a spiral order, starting from the top-left corner and moving in a clockwise direction. This algorithm is commonly used in situations where data is arranged in a grid-like structure, such as images or spreadsheets, and we need to access the elements in a specific order. The main idea behind the algorithm is to incrementally move through the matrix, visiting each element once and printing its value, while updating the boundaries of the matrix as we progress through the spiral.
To implement the spiral print algorithm, we need to maintain four variables representing the boundaries of the current sub-matrix being traversed: top, bottom, left, and right. We start with top and left as 0, and bottom and right set to the dimensions of the matrix minus one. We then iterate through the matrix in a nested loop, printing the elements and updating the boundaries in each iteration. In the first iteration, we print the elements from the top-left to the top-right, then increment the top boundary. In the second iteration, we print the elements from the top-right to the bottom-right and increment the right boundary. In the third iteration, we print the elements from the bottom-right to the bottom-left and decrement the bottom boundary. In the fourth iteration, we print the elements from the bottom-left to the top-left and decrement the left boundary. We continue this process until all the elements in the matrix have been visited and printed.
"""
This program print the matrix in spiral form.
This problem has been solved through recursive way.
Matrix must satisfy below conditions
i) matrix should be only one or two dimensional
ii)column of all the row should be equal
"""
def checkMatrix(a):
# must be
if type(a) == list and len(a) > 0:
if type(a[0]) == list:
prevLen = 0
for i in a:
if prevLen == 0:
prevLen = len(i)
result = True
elif prevLen == len(i):
result = True
else:
result = False
else:
result = True
else:
result = False
return result
def spiralPrint(a):
if checkMatrix(a) and len(a) > 0:
matRow = len(a)
if type(a[0]) == list:
matCol = len(a[0])
else:
for dat in a:
print(dat),
return
# horizotal printing increasing
for i in range(0, matCol):
print(a[0][i]),
# vertical printing down
for i in range(1, matRow):
print(a[i][matCol - 1]),
# horizotal printing decreasing
if matRow > 1:
for i in range(matCol - 2, -1, -1):
print(a[matRow - 1][i]),
# vertical printing up
for i in range(matRow - 2, 0, -1):
print(a[i][0]),
remainMat = [row[1 : matCol - 1] for row in a[1 : matRow - 1]]
if len(remainMat) > 0:
spiralPrint(remainMat)
else:
return
else:
print("Not a valid matrix")
return
# driver code
a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
spiralPrint(a)