Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 해시 테이블
- 정수론
- 트리
- 구현
- 투 포인터
- 슬라이딩 윈도우
- 브루트포스
- 플로이드-워셜
- 맵
- DP
- 그래프
- DFS
- 정렬
- 그리디
- 에라토스테네스의 체
- 세그먼트 트리
- 누적 합
- SSAFY
- 이분 탐색
- 모던 JavaScript 튜토리얼
- JavaScript
- 애드 혹
- boj
- 문자열
- 싸피
- Python
- 13164
- 수학
- 2357
- BFS
Archives
- Today
- Total
흙금이네 블로그
[BOJ] 20046 - Road Reconstruction (Python) 본문
아이디어
다익스트라로 최소 도로 건설 비용을 구해 나간다.
풀이
import sys
from heapq import heappush, heappop
input = sys.stdin.readline
INF = int(1e7)
delta = [(-1, 0), (0, 1), (1, 0), (0, -1)]
def solution():
m, n = map(int, input().split())
board = [tuple(map(int, input().split())) for _ in range(m)]
D = [[INF]*n for _ in range(m)]
heap = []
if board[0][0] != -1 and board[-1][-1] != -1:
heap = [(board[0][0], 0, 0)]
while heap:
cost, r, c = heappop(heap)
if D[r][c] < cost:
continue
for dr, dc in delta:
nr, nc = r+dr, c+dc
if m > nr >= 0 and n > nc >= 0:
if board[nr][nc] != -1 and D[nr][nc] > cost+board[nr][nc]:
D[nr][nc] = cost+board[nr][nc]
heappush(heap, (cost+board[nr][nc], nr, nc))
if D[-1][-1] < INF:
print(D[-1][-1])
else:
print(-1)
solution()
'알고리즘' 카테고리의 다른 글
[BOJ] 7571 - 점 모으기 (Python) (0) | 2023.04.16 |
---|---|
[BOJ] 2026 - 소풍 (Python) (0) | 2023.04.16 |
[BOJ] 14925 - 목장 건설하기 (Python) (0) | 2023.04.15 |
[BOJ] 14466 - 소가 길을 건너간 이유 6 (Python) (0) | 2023.04.15 |
[BOJ] 17828 - 문자열 화폐 (Python) (0) | 2023.04.15 |
Comments