Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Constraints:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
Solution:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
result = []
rows, columns = len(matrix), len(matrix[0])
left = up = 0
right, down = columns-1, rows-1
while len(result) < rows * columns:
# Traverse from left to right.
for col in range(left, right + 1):
result.append(matrix[up][col])
# up to down
for row in range(up+1,down+1):
result.append(matrix[row][right])
# right to left
if up != down:
for col in range(right-1,left-1,-1):
result.append(matrix[down][col])
if left != right:
# Traverse upwards.
for row in range(down - 1, up, -1):
result.append(matrix[row][left])
left += 1
right -= 1
up += 1
down -= 1
return result
'LeetCode' 카테고리의 다른 글
[Leetcode] 23. Merge k Sorted Lists (0) | 2022.01.04 |
---|---|
[Leetcode] 49. Group Anagrams (0) | 2022.01.01 |
448. Find All Numbers Disappeared in an Array (0) | 2021.07.13 |
414. Third Maximum Number (0) | 2021.07.13 |
977. Squares of a Sorted Array (0) | 2021.07.13 |
댓글