ps | |
---|---|
링크 | programmers.co.kr/… |
출처 | 프로그래머스 |
문제 번호 | 1844 |
문제명 | 게임 맵 최단거리 |
레벨 | Level 4 |
분류 |
그래프, BFS |
시간복잡도 | O(nm) |
인풋사이즈 | n<=100, m<=100 |
사용한 언어 | Python |
해결날짜 | 2021/01/22 |
"""Solution code for "Programmers 1844. 게임 맵 최단거리".
- Problem link: https://programmers.co.kr/learn/courses/30/lessons/1844
- Solution link: http://www.teferi.net/ps/problems/programmers/1844
"""
import collections
from typing import Generator, Sequence, Tuple, TypeVar
CellType = TypeVar('CellType')
PosType = Tuple[int, int]
def bfs_in_grid(grid: Sequence[Sequence[CellType]],
empty: CellType,
start: PosType) -> Generator[Tuple[PosType, int], None, None]:
"""Yields (pos, distance) pairs for nodes in BFS-order."""
yield (start, 0)
row_count, col_count = len(grid), len(grid[0])
is_visited = [[False] * col_count for _ in range(row_count)]
queue = collections.deque([(start, 0)])
while queue:
(r, c), dist = queue.popleft()
for dr, dc in ((-1, 0), (0, -1), (0, 1), (1, 0)):
nr, nc = r + dr, c + dc
if not (0 <= nr < row_count and 0 <= nc < col_count and
grid[nr][nc] == empty and not is_visited[nr][nc]):
continue
is_visited[nr][nc] = True
queue.append(((nr, nc), dist + 1))
yield ((nr, nc), dist + 1)
def solution(maps):
target = (len(maps) - 1, len(maps[0]) - 1)
for pos, dist in bfs_in_grid(maps, empty=1, start=(0, 0)):
if pos == target:
return dist + 1
return -1