2019-06-26 15:57:08 +00:00
|
|
|
"""
|
2020-01-18 12:24:33 +00:00
|
|
|
This program print the matrix in spiral form.
|
2019-06-26 15:57:08 +00:00
|
|
|
This problem has been solved through recursive way.
|
|
|
|
|
|
|
|
Matrix must satisfy below conditions
|
|
|
|
i) matrix should be only one or two dimensional
|
2021-08-28 18:07:10 +00:00
|
|
|
ii) number of column of all rows should be equal
|
2019-06-26 15:57:08 +00:00
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2021-08-28 18:07:10 +00:00
|
|
|
from collections.abc import Iterable
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2021-08-28 18:07:10 +00:00
|
|
|
|
|
|
|
def check_matrix(matrix):
|
2019-06-26 15:57:08 +00:00
|
|
|
# must be
|
2021-08-28 18:07:10 +00:00
|
|
|
if matrix and isinstance(matrix, Iterable):
|
|
|
|
if isinstance(matrix[0], Iterable):
|
|
|
|
prev_len = 0
|
|
|
|
for row in matrix:
|
|
|
|
if prev_len == 0:
|
|
|
|
prev_len = len(row)
|
2019-06-26 15:57:08 +00:00
|
|
|
result = True
|
|
|
|
else:
|
2021-08-28 18:07:10 +00:00
|
|
|
result = prev_len == len(row)
|
2019-06-26 15:57:08 +00:00
|
|
|
else:
|
|
|
|
result = True
|
|
|
|
else:
|
|
|
|
result = False
|
2021-08-28 18:07:10 +00:00
|
|
|
|
2019-06-26 15:57:08 +00:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def spiralPrint(a):
|
2021-08-28 18:07:10 +00:00
|
|
|
if check_matrix(a) and len(a) > 0:
|
2019-06-26 15:57:08 +00:00
|
|
|
matRow = len(a)
|
2021-08-28 18:07:10 +00:00
|
|
|
if isinstance(a[0], Iterable):
|
2019-06-26 15:57:08 +00:00
|
|
|
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]),
|
2019-10-05 05:14:13 +00:00
|
|
|
remainMat = [row[1 : matCol - 1] for row in a[1 : matRow - 1]]
|
2019-06-26 15:57:08 +00:00
|
|
|
if len(remainMat) > 0:
|
|
|
|
spiralPrint(remainMat)
|
|
|
|
else:
|
|
|
|
return
|
|
|
|
else:
|
|
|
|
print("Not a valid matrix")
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
# driver code
|
2021-08-28 18:07:10 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
a = ([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12])
|
|
|
|
spiralPrint(a)
|