Spiral Matrix - LeetCode
Can you solve this real interview question? Spiral Matrix - Given an m x n matrix, return all elements of the matrix in spiral order. Example 1: [https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg] Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Outpu
leetcode.com
아이디어
방향 벡터(dv)를 사용해서 풀었다.
시작점(0,0)에서 우측 방향으로 이동하다가 범위를 벗어나거나 이미 방문한 곳(visited[nx][ny] == 1)이면 방향을 시계방향으로 90도 돌려준 뒤(d = (d+1)%4) 해당 방향으로 이동하도록 했다.
전체 코드
# 12:11 ~ 12:24(13")
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
dv = [(-1, 0), (0, 1), (1, 0), (0, -1)]
N, M = len(matrix), len(matrix[0])
visited = [[0 for _ in range(M)] for y in range(N)]
x, y, d = 0, 0, 1
visited[0][0] = 1
answer = [matrix[0][0], ]
while True:
if len(answer) == N*M:
break
nx = x + dv[d][0]
ny = y + dv[d][1]
if nx < 0 or nx >= N or ny < 0 or ny >= M or visited[nx][ny] == 1:
d = (d+1) % 4
continue
answer.append(matrix[nx][ny])
visited[nx][ny] = 1
x, y = nx, ny
return answer
'Coding Test > Python' 카테고리의 다른 글
[프로그래머스] 폰켓몬(level1, python) (0) | 2024.01.10 |
---|---|
[프로그래머스] 완주하지 못한 선수 (level1, python) (0) | 2024.01.10 |
[백준] 17779번: 게리맨더링 2 (골드3, 파이썬) (1) | 2024.01.08 |
[백준] 17140번: 이차원 배열과 연산 (골드4, 파이썬) (0) | 2024.01.06 |
[백준] 17144번: 미세먼지 안녕! (골드4, 파이썬) (1) | 2024.01.05 |