Description Given an M*N matrix (M rows, N columns) in a two-dimensional list, return all the elements of the matrix in a spiral order, and output them in a list, with each element separated by commas.
For example, given a matrix as follows:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
then it should return [1,2,3,6,9,8 according to the spiral shape ,7,4,5]
The frame reference of the program is as follows:
def SpiralOrder(matrix):
...
matrix = eval(input())
res = SpiralOrder(matrix)
print(res)
Test case:
Case 1:
Input:
[[1,2,3],[4,5,6],[7,8,9]]
Output:
[1, 2, 3, 6, 9, 8, 7, 4, 5]
Use Case 2:
Input:
[]
Output:
[]
Analysis:
Refer to this blog post: http://blog.csdn.net/alexingcool/article/details/6779330
def SpiralOrder(matrix):
ans=[]
Size=len(matrix)
i=0
while i<Size:
j1=i
while j1<Size-i:
ans.append(matrix[i][j1])
j1+=1
j2=i+1
while j2<Size-i:
ans.append(matrix[j2][Size-i-1])
j2+=1
j3=Size-i-2
while j3>=i:
ans.append(matrix[Size-i-1][j3])
j3-=1
j4=Size-i-2
while j4>i:
ans.append(matrix[j4][i])
j4-=1
i+=1
return ans
matrix = eval(input())
res=SpiralOrder(matrix)
print(res)