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
I think DFS can be the easier way to do this. However, I want to avoid recursion. Therefore, the solution I had is below.
from enum import Enum
class Direction(Enum):
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m = len(matrix)
n = len(matrix[0])
x = y = 0
way = Direction.RIGHT
result = [matrix[0][0]]
matrix[0][0] = None
total = m * n
while len(result) < total:
if way is Direction.RIGHT:
if x + 1 == n or matrix[y][x+1] == None:
way = Direction.DOWN
else:
x += 1
result.append(matrix[y][x])
matrix[y][x] = None
if way is Direction.DOWN:
if y + 1 == m or matrix[y+1][x] == None:
way = Direction.LEFT
else:
y += 1
result.append(matrix[y][x])
matrix[y][x] = None
if way is Direction.LEFT:
if x - 1 < 0 or matrix[y][x-1] == None:
way = Direction.UP
else:
x -= 1
result.append(matrix[y][x])
matrix[y][x] = None
if way is Direction.UP:
if y - 1 < 0 or matrix[y-1][x] == None:
way = Direction.RIGHT
else:
y -= 1
result.append(matrix[y][x])
matrix[y][x] = None
return result
搶先發佈留言