forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path3.py
47 lines (40 loc) Β· 1.65 KB
/
3.py
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])