Dijkstra

Dijkstra

演算法

邏輯

上一篇我寫了BFS,但是不是每一次點到點的距離都是1,有時候可能會有過路費的問題,所以我們必須將他考量進去,這事後我們就要用dijkstra,痾…如果你想問我怎麼唸的話,我也不知道哈哈,你可以去問問看資訊老師?好廢話不多說,簡單來說他就是跟BFS很像的東西,一樣會一格去走訪,只是我們要注意,有時候繞路可能會比較省過路費,所以我們如果找到比他還便宜的路線我們就會加進去我們的queue裡面;講到queue,我們這次不用queue,用priority queue,不一樣的就是他會自動將最小的東西排到最前面。
byai

題目

實際上做一下應該比較有感覺:

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
from sys import stdin
import heapq

n = int(stdin.readline())
for i in range(n):
N = int(stdin.readline())
M = int(stdin.readline())
mapp = []
for k in range(N):
mapp.append(list(map(int, stdin.readline().split())))
#pq = [[0, 0, 0]] #雖然用一般arr 但之後取min?
pq = []
heapq.heappush(pq, [mapp[0][0], 0, 0])
used = [[0 for i in range(M)]for i in range(N)] #red
ans = [[999 for i in range(M)]for i in range(N)]
ans[0][0] = mapp[0][0]
while pq:
cost, x, y = heapq.heappop(pq)
#used[x][y] = 1
if used[x][y] == 1:
continue
used[x][y] = 1
if x == N - 1 and y == M - 1:
print(ans[x][y])
break
if x + 1 < N and used[x+1][y] == 0:
if cost + mapp[x+1][y] < ans[x+1][y] and used[x+1][y] == 0:
heapq.heappush(pq, [cost+mapp[x+1][y], x+1, y])
ans[x+1][y] = cost + mapp[x+1][y]
if x - 1 >= 0 and used[x-1][y] == 0 :
if cost + mapp[x-1][y] < ans[x-1][y] and used[x-1][y] == 0:
heapq.heappush(pq, [cost+mapp[x-1][y], x-1, y])
ans[x-1][y] = cost + mapp[x-1][y]
if y + 1 < M and used[x][y+1] == 0 :
if cost + mapp[x][y+1] < ans[x][y+1] and used[x][y+1] == 0:
heapq.heappush(pq, [cost+mapp[x][y+1], x, y+1])
ans[x][y+1] = cost + mapp[x][y+1]
if y - 1 >= 0 and used[x][y-1] == 0:
if cost + mapp[x][y-1] < ans[x][y-1] and used[x][y-1] == 0:
heapq.heappush(pq, [cost+mapp[x][y-1], x, y-1])
ans[x][y-1] = cost + mapp[x][y-1]

大概就像這樣,如果不知道heapq怎麼用可以去查一下,因為我一開始也不知道哈哈。