forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3.py
More file actions
47 lines (40 loc) ยท 1.65 KB
/
3.py
File metadata and controls
47 lines (40 loc) ยท 1.65 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import heapq
import sys
input = sys.stdin.readline
INF = int(1e9) # ๋ฌดํ์ ์๋ฏธํ๋ ๊ฐ์ผ๋ก 10์ต์ ์ค์
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
# ์ ์ฒด ํ
์คํธ ์ผ์ด์ค(Test Case)๋งํผ ๋ฐ๋ณต
for tc in range(int(input())):
# ๋
ธ๋์ ๊ฐ์๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
n = int(input())
# ์ ์ฒด ๋งต ์ ๋ณด๋ฅผ ์
๋ ฅ๋ฐ๊ธฐ
graph = []
for i in range(n):
graph.append(list(map(int, input().split())))
# ์ต๋จ ๊ฑฐ๋ฆฌ ํ
์ด๋ธ์ ๋ชจ๋ ๋ฌดํ์ผ๋ก ์ด๊ธฐํ
distance = [[INF] * n for _ in range(n)]
x, y = 0, 0 # ์์ ์์น๋ (0, 0)
# ์์ ๋
ธ๋๋ก ๊ฐ๊ธฐ ์ํ ๋น์ฉ์ (0, 0) ์์น์ ๊ฐ์ผ๋ก ์ค์ ํ์ฌ, ํ์ ์ฝ์
q = [(graph[x][y], x, y)]
distance[x][y] = graph[x][y]
# ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ์ํ
while q:
# ๊ฐ์ฅ ์ต๋จ ๊ฑฐ๋ฆฌ๊ฐ ์งง์ ๋
ธ๋์ ๋ํ ์ ๋ณด๋ฅผ ๊บผ๋ด๊ธฐ
dist, x, y = heapq.heappop(q)
# ํ์ฌ ๋
ธ๋๊ฐ ์ด๋ฏธ ์ฒ๋ฆฌ๋ ์ ์ด ์๋ ๋
ธ๋๋ผ๋ฉด ๋ฌด์
if distance[x][y] < dist:
continue
# ํ์ฌ ๋
ธ๋์ ์ฐ๊ฒฐ๋ ๋ค๋ฅธ ์ธ์ ํ ๋
ธ๋๋ค์ ํ์ธ
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
# ๋งต์ ๋ฒ์๋ฅผ ๋ฒ์ด๋๋ ๊ฒฝ์ฐ ๋ฌด์
if nx < 0 or nx >= n or ny < 0 or ny >= n:
continue
cost = dist + graph[nx][ny]
# ํ์ฌ ๋
ธ๋๋ฅผ ๊ฑฐ์ณ์, ๋ค๋ฅธ ๋
ธ๋๋ก ์ด๋ํ๋ ๊ฑฐ๋ฆฌ๊ฐ ๋ ์งง์ ๊ฒฝ์ฐ
if cost < distance[nx][ny]:
distance[nx][ny] = cost
heapq.heappush(q, (cost, nx, ny))
print(distance[n - 1][n - 1])