Added spiral solution
This commit is contained in:
parent
2a297109d8
commit
6bed97c143
1 changed files with 60 additions and 0 deletions
60
spiral.py
Executable file
60
spiral.py
Executable file
|
@ -0,0 +1,60 @@
|
|||
#!/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)
|
Reference in a new issue