LeetCode #54: Spiral Matrix
https://leetcode.com/problems/spiral-matrix/
The problem requires us to return a list of integers in the order of the elements visited in a clockwise spiral order from a given matrix. We can solve this by traversing the matrix in a spiral order by dividing the matrix into four directions – left to right, top to bottom, right to left, and bottom to top. We keep track of the direction of traversal and stop traversing once we reach the last element of the matrix.
- Initialize four variables
left
,right
,up
, anddown
to represent the boundaries of our matrix.left
andup
are initially set to 0, andright
anddown
are set to the last column index and the last row index respectively. - Create an empty list
res
to store the elements of the matrix in a spiral order. - While the length of
res
is less than the total number of elements in the matrix, do the following:- Traverse from
left
toright
along theup
row and add each element tores
. - Traverse from
up + 1
todown
along theright
column and add each element tores
. - Traverse from
right - 1
toleft
along thedown
row only ifup
anddown
are not the same, and add each element tores
. - Traverse from
down - 1
toup + 1
along theleft
column only ifleft
andright
are not the same, and add each element tores
. - Update the boundaries by incrementing
left
andup
, and decrementingright
anddown
.
- Traverse from
- Return
res
which now contains the elements of the matrix in a clockwise spiral order.
Here’s the solution code:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
left = 0
rows = len(matrix)
columns = len(matrix[0])
right = columns-1
up = 0
down = rows-1
res = []
while len(res) < rows*columns:
for col in range(left, right+1):
res.append(matrix[up][col])
for row in range(up+1, down+1):
res.append(matrix[row][right])
if up != down:
for col in range(right-1, left-1, -1):
res.append(matrix[down][col])
if left != right:
for row in range(down-1, up, -1):
res.append(matrix[row][left])
left+=1
right-=1
up+=1
down-=1
return res
Time and Space Complexity
Time complexity: O(m*n) where m and n are the dimensions of the matrix, as we need to visit every element in the matrix.
Space complexity: O(m*n) as we create a list to store the elements of the matrix in a spiral order.