일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 매일
- 잡생각
- 영어원서읽기
- 링피트
- 30분
- 쓰릴오브파이트
- 스탭퍼
- 화상영어
- 파비최
- 괜찮음
- 운동
- realclass
- 10분
- 리얼 클래스
- Daily Challenge
- 뭐든
- 프로젝트
- English
- Writing
- leetcode
- 영어공부
- 개발자
- 읽기
- 3줄정리
- 미드시청
- FIT XR
- 사이드
- Problem Solving
- 월간
- 만화도
Archives
- Today
- Total
파비의 매일매일 공부기록
Today's Challenge 본문
https://leetcode.com/problems/shortest-path-in-binary-matrix/
Shortest Path in Binary Matrix - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
offset을 tuple의 묶음으로 표시할 수 있는 걸 배움
나머지는 bfs의 연속인 듯. 일단 최소 비용을 1로 놓고 시작. (2 x 2 인 경우)
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0] or grid[-1][-1]:
return -1
n = len(grid)
offsets = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
qu = deque()
qu.append((0, 0))
visited = {(0, 0)}
def get_adj(x, y):
for x_offset, y_offset in offsets:
nx = x + x_offset
ny = y + y_offset
if 0 <= nx < n and 0 <= ny < n and not grid[nx][ny] and (nx, ny) not in visited:
yield (nx, ny)
cur = 1
while qu:
l = len(qu)
for _ in range(l):
r, c = qu.popleft()
if r == n-1 and c == n-1:
return cur
for p in get_adj(r, c):
visited.add(p)
qu.append(p)
cur += 1
return -1
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
Today's Challenge (0) | 2022.05.18 |
---|---|
Today's Challenge (0) | 2022.05.17 |
Today's Challenge (0) | 2022.05.15 |
Today's Challenge (0) | 2022.05.14 |
Today's Challenge (0) | 2022.05.13 |
Comments