Spiral Order Matrix
matrix of m * n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example:
Given the following matrix:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
You should return
[1,2,3,6,9,8,7,4,5]
Solution:
class Solution:
# @param A : tuple of list of integers
# @return a list of integers
def spiralOrder(self, A):
mat=[]
b=(len(A)-1)
r=(len(A[0])-1)
l=t=diri=0
while(l<=r and t<=b):
if(diri==0):
for k in range(l,r+1):
mat.append(A[t][k])
t+=1
elif diri==1:
for k in range(t,b+1):
mat.append(A[k][r])
r-=1
elif(diri==2):
for k in range(r,l-1,-1):
mat.append(A[b][k])
b-=1
elif(diri==3):
for k in range(b,t-1,-1):
mat.append(A[k][l])
l+=1
diri=(diri+1)%4
return mat[:]
Solution Credits:
Comments
Post a Comment