-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.py
More file actions
53 lines (42 loc) · 1.18 KB
/
Graph.py
File metadata and controls
53 lines (42 loc) · 1.18 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
48
49
50
51
52
53
import heapq
class Graph:
def __init__(self):
self.edge = {}
self.cost = {}
self.vertex = set()
return
def addEdgeCost(self, i, j, c, directed=False):
self.vertex.add(i)
self.vertex.add(j)
if i not in self.edge:
self.edge[i] = []
self.edge[i].append(j)
self.cost[(i, j)] = c
if directed is False:
return
if j not in self.edge:
self.edge[j] = []
self.edge[j].append(i)
self.cost[(j, i)] = c
return
def dijkstra(g: Graph, s=None) -> dict:
def solve(v_start):
ret_cost = {v: float("inf") for v in g.vertex}
ret_cost[v_start] = 0
heap = [(0, v_start)]
while heap:
_, v_from = heapq.heappop(heap)
for v_to in g.edge.get(v_from, []):
nc = ret_cost[v_from] + g.cost[(v_from, v_to)]
if ret_cost[v_to] > nc:
ret_cost[v_to] = nc
heapq.heappush(heap, (nc, v_to))
return ret_cost
if s is None:
V = g.vertex
else:
V = [s]
ret = {}
for v in V:
ret[v] = solve(v)
return ret