알고리즘 문제/Leetcode
54. Spiral Matrix
BEstyle
2023. 5. 2. 14:52
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
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
result = []
top=0
bottom=len(matrix)-1
left=0
rightlen(matrix[0])-1
direction = 0
while top <= bottom and left <= right:
if direction == 0:
for i in range(left, right+1):
result.append(matrix[top][i])
top += 1
elif direction == 1:
for i in range(top, bottom+1):
result.append(matrix[i][right])
right -= 1
elif direction == 2:
for i in range(right, left-1, -1):
result.append(matrix[bottom][i])
bottom -= 1
elif direction == 3:
for i in range(bottom, top-1, -1):
result.append(matrix[i][left])
left += 1
direction = (direction+1) % 4
return result