LeetCode 솔루션 분류
[5/10] 59. Spiral Matrix II
본문
관련자료
-
링크
댓글 2
JJJJJJJJJJ님의 댓글
- 익명
- 작성일
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
ret = [[-1 for x in range(n)] for x in range(n)]
cur_val, cur_dir = 0, 0
directions = [(0,1), (1,0), (0,-1), (-1,0)]
y, x = 0, 0
prev_y, prev_x = 0, 0
while cur_val < n*n:
while x >= 0 and x < n and y >= 0 and y < n and ret[y][x] == -1:
cur_val += 1
ret[y][x] = cur_val
prev_y, prev_x = y, x
y = prev_y + directions[cur_dir][0]
x = prev_x + directions[cur_dir][1]
cur_dir = (cur_dir +1) % 4
y = prev_y + directions[cur_dir][0]
x = prev_x + directions[cur_dir][1]
return ret