-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra.py
73 lines (49 loc) · 1.45 KB
/
dijkstra.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import heapq
from functools import total_ordering
@total_ordering
class Way:
def __init__(self, from_, to, cost):
self.from_ = from_
self.to = to
self.cost = cost
self.total_cost = cost
def __eq__(self, other):
return self.total_cost == other.total_cost
def __lt__(self, other):
return self.total_cost < other.total_cost
def __repr__(self):
return f'Way from:{self.from_}, to:{self.to}, cost:{self.cost}, total_cost:{self.total_cost}'
n, start, finish = map(int, input().split())
graph = {}
cur = []
done = [-1] * (n + 1)
done[start] = 0
for i in range(1, n + 1):
nums = [int(j) for j in input().split()]
for to in range(1, n + 1):
if i not in graph:
graph[i] = []
cost = nums[to - 1]
if cost == -1 or i == to:
continue
item = Way(i, to, cost)
graph[i].append(item)
if i == start:
heapq.heappush(cur, item)
saw = {start}
while True:
if not cur:
break
way = heapq.heappop(cur)
if way.to in saw:
continue
done[way.to] = done[way.from_] + way.cost
saw.add(way.to)
if way.to == finish:
break
for new_way in graph[way.to]:
if new_way.to in saw:
continue
new_way.total_cost += way.total_cost
heapq.heappush(cur, new_way)
print(done[finish])