- Notifications
You must be signed in to change notification settings - Fork 845
/
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
importheapq
importsys
input=sys.stdin.readline
INF=int(1e9) # 무한을 의미하는 값으로 10억을 설정
dx= [-1, 0, 1, 0]
dy= [0, 1, 0, -1]
# 전체 테스트 케이스(Test Case)만큼 반복
fortcinrange(int(input())):
# 노드의 개수를 입력받기
n=int(input())
# 전체 맵 정보를 입력받기
graph= []
foriinrange(n):
graph.append(list(map(int, input().split())))
# 최단 거리 테이블을 모두 무한으로 초기화
distance= [[INF] *nfor_inrange(n)]
x, y=0, 0# 시작 위치는 (0, 0)
# 시작 노드로 가기 위한 비용은 (0, 0) 위치의 값으로 설정하여, 큐에 삽입
q= [(graph[x][y], x, y)]
distance[x][y] =graph[x][y]
# 다익스트라 알고리즘을 수행
whileq:
# 가장 최단 거리가 짧은 노드에 대한 정보를 꺼내기
dist, x, y=heapq.heappop(q)
# 현재 노드가 이미 처리된 적이 있는 노드라면 무시
ifdistance[x][y] <dist:
continue
# 현재 노드와 연결된 다른 인접한 노드들을 확인
foriinrange(4):
nx=x+dx[i]
ny=y+dy[i]
# 맵의 범위를 벗어나는 경우 무시
ifnx<0ornx>=norny<0orny>=n:
continue
cost=dist+graph[nx][ny]
# 현재 노드를 거쳐서, 다른 노드로 이동하는 거리가 더 짧은 경우
ifcost<distance[nx][ny]:
distance[nx][ny] =cost
heapq.heappush(q, (cost, nx, ny))
print(distance[n-1][n-1])