-
지형 이동코딩 테스트/Level 4 2023. 1. 25. 11:38반응형
https://school.programmers.co.kr/learn/courses/30/lessons/62050
queue를 이용.
from heapq import heappop, heappush def solution(land, height): answer = 0 que = [(0, 0, 0)] visited = set() while que: p, y, x = heappop(que) if (y, x) in visited: continue visited.add((y, x)) answer += p for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)): next_y, next_x = y + dy, x + dx if not (len(land) > next_y >= 0 and len(land) > next_x >= 0): continue if (diff := abs(land[y][x] - land[next_y][next_x])) <= height: next_p = 0 else: next_p = diff heappush(que, (next_p, next_y, next_x)) return answer
굳이 줄이려면 줄일 수도 있겠으나.. 가독성이..
from heapq import heappop, heappush def solution(land, height): answer = 0 que = [(0, 0, 0)] visited = set() while que: p, y, x = heappop(que) if (y, x) not in visited: visited.add((y, x)) answer += p for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)): next_y, next_x = y + dy, x + dx if len(land) > next_y >= 0 and len(land) > next_x >= 0: heappush(que, (0 if (diff := abs(land[y][x] - land[next_y][next_x])) <= height else diff, next_y, next_x)) return answer
반응형