Given an m x n matrix, return all elements of the matrix in spiral order.
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5]
class Solution:
def spiralOrder(self, m: List[List[int]]) -> List[int]:
ans = []
l, r = 0, len(m[0])
t, b = 0, len(m)
while l < r and t < b:
# top row cover
for i in range(l,r):
ans.append(m[t][i])
t += 1
# right col cover
for i in range(t,b):
ans.append(m[i][r-1])
r -= 1
# no jhanjat of 1 x n or n x 1
if not (l < r and t < b):
break
# bottom row cover
for i in range(r-1,l-1,-1):
ans.append(m[b-1][i])
b -= 1
# left col cover
for i in range(b-1,t-1,-1):
ans.append(m[i][l])
l +=1
return ans
Explaination :
Comments
Post a Comment