Skip to content

Commit ad065c8

Browse files
committed
[BOJ] #4485. 녹색 옷을 입은 애가 젤다지? / 골드4 / 그래프, 다익스트라 / 60분 / 실패
1 parent 4310966 commit ad065c8

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import sys
2+
import heapq
3+
4+
input = sys.stdin.readline
5+
6+
# 오른쪽, 아래, 위, 왼쪽
7+
dx = [0, 1, -1, 0]
8+
dy = [1, 0, 0, -1]
9+
10+
# 정답 출력을 위한 테스트 케이스 번호 변수
11+
cnt = 0
12+
13+
# 첫 번째 테스트 케이스의 동굴 크기
14+
n = int(input())
15+
16+
while n != 0:
17+
cnt += 1
18+
19+
# 동굴의 각 칸에 있는 도둑루피의 크기를 board에 저장
20+
board = [list(map(int, input().split())) for _ in range(n)]
21+
heap = []
22+
dist = [[1e9] * n for _ in range(n)]
23+
dist[0][0] = board[0][0]
24+
25+
# 시작점 정보를 (비용, y, x) 형태로 힙에 추가
26+
heapq.heappush(heap, (board[0][0], 0, 0))
27+
28+
# 다익스트라 알고리즘
29+
while heap:
30+
distance, y, x = heapq.heappop(heap)
31+
32+
# 최소 비용 우선 탐색이므로, 도착점 [n-1][n-1]에 도착하면 바로 출력
33+
if y == n - 1 and x == n - 1:
34+
print(f"Problem {cnt}: {distance}")
35+
n = int(input())
36+
break
37+
38+
# 상하좌우 네 방향에 대해 탐색
39+
for i in range(4):
40+
ny = y + dy[i] # 새로운 y 좌표를 계산
41+
nx = x + dx[i] # 새로운 x 좌표를 계산
42+
43+
# 새로운 좌표가 동굴 내부에 있는지 확인
44+
if 0 <= ny < n and 0 <= nx < n:
45+
# 인접한 칸까지 이동했을 때의 누적 비용을 계산
46+
cost = distance + board[ny][nx]
47+
48+
# 만약 현재 저장된 비용보다 새로운 비용이 작으면 업데이트
49+
if dist[ny][nx] > cost:
50+
dist[ny][nx] = cost
51+
# 새로운 비용과 좌표를 우선순위 큐에 추가
52+
heapq.heappush(heap, (cost, ny, nx))

0 commit comments

Comments
 (0)