LeetCode 솔루션 분류
[5/9] 54. Spiral Matrix
본문
관련자료
-
링크
댓글 3
JJJJJJJJJJ님의 댓글
- 익명
- 작성일
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
spiral = []
m, n = len(matrix), len(matrix[0])
total = m * n
directions = [(0,1), (1,0), (0, -1), (-1, 0)]
cur_directions = 0
cur = (0,0)
curlen = 0
while curlen < total:
spiral.append(matrix[cur[0]][cur[1]])
curlen += 1
matrix[cur[0]][cur[1]] = -101
next_pos = (cur[0] + directions[cur_directions][0], cur[1] + directions[cur_directions][1])
if next_pos[0] < 0 or next_pos[1] < 0 or next_pos[0] == m or next_pos[1] == n or -101 == matrix[next_pos[0]][next_pos[1]]:
cur_directions = (cur_directions + 1) % 4
cur = (cur[0] + directions[cur_directions][0], cur[1] + directions[cur_directions][1])
return spiral
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
spiral = []
m, n = len(matrix), len(matrix[0])
total = m * n
directions = [(0,1), (1,0), (0, -1), (-1, 0)]
cur_directions = 0
cur = (0,0)
curlen = 0
while curlen < total:
spiral.append(matrix[cur[0]][cur[1]])
curlen += 1
matrix[cur[0]][cur[1]] = -101
next_pos = (cur[0] + directions[cur_directions][0], cur[1] + directions[cur_directions][1])
if next_pos[0] < 0 or next_pos[1] < 0 or next_pos[0] == m or next_pos[1] == n or -101 == matrix[next_pos[0]][next_pos[1]]:
cur_directions = (cur_directions + 1) % 4
cur = (cur[0] + directions[cur_directions][0], cur[1] + directions[cur_directions][1])
return spiral