Leetcode # 54. Spiral Matrix
https://leetcode.com/problems/spiral-matrix
Solution
Time Complexity: O(len(matrix) * len(matrix[0]))
Space Complexity: O(len(matrix) * len(matrix[0]))
(The input and output generally do not count towards the space complexity.)
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
def _spiralOrder(matrix, start, size):
if size[0] < 1 or size[1] < 1:
return []
spiral_order = []
for j in range(size[1]):
x = start[0] + j
y = start[1]
spiral_order.append(matrix[y][x])
for i in range(size[0] - 1):
x = start[0] + size[1] - 1
y = start[1] + 1 + i
spiral_order.append(matrix[y][x])
if size[0] > 1 and size[1] > 1:
for j in range(size[1] - 1):
x = start[0] + size[1] - 2 - j
y = start[1] + size[0] - 1
spiral_order.append(matrix[y][x])
for i in range(size[0] - 2):
x = start[0]
y = start[1] + size[0] - 2 - i
spiral_order.append(matrix[y][x])
return spiral_order + \
_spiralOrder(matrix,
(start[0] + 1, start[1] + 1),
( size[0] - 2, size[1] - 2))
return _spiralOrder(matrix, (0, 0), (len(matrix), len(matrix[0])))
Last Updated on 2023/08/16 by A1go