문제 링크
풀이 과정
전체 코드
from heapq import heappush, heappop, heapify
def isin_boundary(y, x, rows, cols):
return (0 <= y < rows) and (0 <= x < cols)
def solution(land, height):
answer = 0
delta = [(-1, 0), (1, 0), (0, -1), (0, 1)] # 상, 하, 좌, 우
rows, cols = len(land), len(land[0])
heap = [(0, 0, 0)] # cost, y, x
heapify(heap)
visited = [[0 for _ in range(cols)] for _ in range(rows)]
while heap:
cost, cy, cx = heappop(heap)
if visited[cy][cx] == 0:
visited[cy][cx] = 1
answer += cost
for dy, dx in delta:
ny, nx = cy+dy, cx+dx
if isin_boundary(ny, nx, rows, cols):
height_diff = abs(land[cy][cx] - land[ny][nx])
if height_diff <= height: ncost = 0
else: ncost = height_diff
heappush(heap, (ncost, ny, nx))
return answer
Python
복사