Skip to content

Commit 740638e

Browse files
committed
[BOJ] #4485.녹색 옷 입은 애가 젤다지? / 골드4 / 60(X)
1 parent ffd1de1 commit 740638e

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import sys
2+
input = sys.stdin.readline
3+
import heapq
4+
5+
# 방향 벡터 (상, 하, 좌, 우)
6+
dx = [-1, 1, 0, 0]
7+
dy = [0, 0, -1, 1]
8+
9+
def dijkstra(N, cave):
10+
INF = float('inf')
11+
dist = [[INF] * N for _ in range(N)]
12+
13+
# 우선순위 큐 (손실 루피, x, y)
14+
pq = []
15+
heapq.heappush(pq, (cave[0][0], 0, 0))
16+
dist[0][0] = cave[0][0]
17+
18+
while pq:
19+
rupee, x, y = heapq.heappop(pq)
20+
21+
# 목적지 도착 시 종료
22+
if x == N - 1 and y == N - 1:
23+
return rupee
24+
# 현재 저장된 최소 비용보다 크면 무시
25+
if rupee > dist[x][y]:
26+
continue
27+
for i in range(4):
28+
nx, ny = x + dx[i], y + dy[i]
29+
30+
if 0 <= nx < N and 0 <= ny < N:
31+
new_cost = rupee + cave[nx][ny]
32+
if new_cost < dist[nx][ny]:
33+
dist[nx][ny] = new_cost
34+
heapq.heappush(pq, (new_cost, nx, ny))
35+
36+
case_num = 1
37+
38+
while True:
39+
N = int(input().strip())
40+
if N == 0:
41+
break
42+
cave = [list(map(int, input().split())) for _ in range(N)]
43+
result = dijkstra(N, cave)
44+
print(f"Problem {case_num}: {result}")
45+
case_num += 1

0 commit comments

Comments
 (0)