This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
ProgrammingChallenges/spiral.py

61 lines
1.3 KiB
Python
Raw Normal View History

2019-03-28 15:56:59 +00:00
#!/usr/bin/env python3
import sys
def parsematrix(m, n):
Mat = []
for i in range(m):
A = sys.stdin.readline().split()
row = []
for j in range(n):
row.append(int(A[j]))
Mat.append(row)
return Mat
def printmatrix(Mat, m, n):
if m == 0 or n == 0:
return
i = 0
min_j = -1
max_j = n
min_i = -1
max_i = m
j = 0
direction = 0 # 0 right, 1 down, 2 left, 3 up
while i > min_i and i < max_i and j < max_j and j > min_j:
if i == 0 and j == 0:
print(Mat[i][j], end="")
else:
print(" " + str(Mat[i][j]), end="")
if direction == 0 and j == n - i - 1:
min_i = i
direction = 1
if direction == 1 and i == m - (n - j):
max_j = j
direction = 2
if direction == 2 and j == m - i - 1:
max_i = i
direction = 3
if direction == 3 and j == i - 1:
min_j = j
direction = 0
if direction == 0:
j = j + 1
elif direction == 1:
i = i + 1
elif direction == 2:
j = j - 1
else:
i = i - 1
if __name__ == "__main__":
A = sys.stdin.readline().split()
m = int(A[0])
n = int(A[1])
Mat = parsematrix(m, n)
printmatrix(Mat, m, n)