티스토리 뷰
링크는 https://leetcode.com/problems/spiral-matrix/description/
# 문제이해
정수로 된 숫자 배열이 주어지면, 우 -> 하 -> 좌 -> 상 방향으로 돌면서, 숫자 순서를 아웃풋 하는 방식.
# 생각해본 방법
모든 숫자를 하나하나 완전 탐색해야 하지 않을까 생각
요론식의 수도 코드를 생각했다.
checked = [[]]
direction [right, down, left, right] # right(0,1)
cnt = 0
direction[cnt % len(direction)]
x, y = 0, 0 # start
while cnt:
dx, dy = direction[cnt % len(direction)]
nx += dx
ny += dy
if 0 <= nx <= m and 0 <= ny <=n and checked[nx][ny]:
...
else:
cnt += 1
# Try 1. 성공
34ms Beats 67.10%
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
answer = []
checked = [[0] * n for _ in range(m)]
right, down, left, up = (0, 1), (1,0), (0, -1), (-1, 0)
direction = [right, down, left, up]
x, y = 0, 0
cnt = 0
# start
answer.append(matrix[0][0])
checked[0][0] = 1
while len(answer) != m*n:
dy, dx = direction[cnt%len(direction)]
nx = x + dx
ny = y + dy
if (0 <= nx < n and 0 <= ny < m) and checked[ny][nx] == 0:
answer.append(matrix[ny][nx])
checked[ny][nx] = 1
x, y = nx, ny
else:
cnt += 1
return answer
# 생각해본 방법 2
python 이니까, stack/pop 을 잘 사용하면 쉽게 갈 수 있지 않을까 싶었다. right 일때는 가장 위의 배열 전체를 쭉 훑으니 pop 해주고,
down 은 배열들의 가장 마지막 원소를 pop 해주는 식으로 stack / pop 구조를 이용해보기로
# Try 1. 성공
Runtime - 26ms Beats96.67%
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
length = len(matrix[0]) * len(matrix)
answer = []
direction = ['right', 'down', 'left', 'up']
cnt = 0
while len(answer) != length:
if direction[cnt%len(direction)] == 'right':
arr = matrix.pop(0)
answer.extend(arr)
elif direction[cnt%len(direction)] == 'down':
for arr in matrix:
answer.append(arr.pop())
elif direction[cnt%len(direction)] == 'left':
arr = matrix.pop()
answer.extend(arr[::-1])
else: #up
tmp = []
for arr in matrix:
tmp.append(arr.pop(0))
answer.extend(tmp[::-1])
cnt += 1
return answer
로 풀이했는데 Runtime 이 빨라졌다 신기하네.
'Algorithm > problems' 카테고리의 다른 글
Leetcode 53. Maximum Subarray (0) | 2024.08.06 |
---|---|
Leetcode 295. Find Median from Data Stream (0) | 2024.07.04 |
Leetcode 17. Letter Combinations of a Phone Number (0) | 2024.06.25 |
Leetcode 334. Increasing Triplet Subsequence (0) | 2024.06.24 |
프로그래머스, 다리를 지나는 트럭 (Python) (1) | 2024.03.08 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- arp응답
- 알고리즘
- leetcode 54. spiral matrix
- leetcode 295
- 122. best time to buy and sell stock ii
- leetcode
- 광역망
- 네트워크허브
- 이더넷프로토콜
- 네트워크성능평가
- 블루/그린
- leetcode334
- 네트워크처리율
- 네트워크분류
- 프로그래머스
- leetcode 17. letter combinations of a phone number
- Algorithm
- 클래스리스주소체계
- 54. spiral matrix
- 네트워크패킷로스
- 이더넷뜻
- 이더넷이란
- leetcode 295. find median from data stream
- letter case permutation
- 롤링업데이트
- 인터넷프로토콜이란
- 네트워크정의
- increasing-triplet-subsequence
- 클래스풀주소체계
- 테라폼구축
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
글 보관함