-
Notifications
You must be signed in to change notification settings - Fork 1
/
Graph.py
66 lines (56 loc) · 1.65 KB
/
Graph.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
from pythonds.graphs import PriorityQueue
class Graph:
def __init__(self):
self.V = []
self.E = []
self.cost = {}
self.neighbours = {}
def addVertex(self, vertex):
self.V.append(vertex)
self.cost[vertex] = 1
self.neighbours[vertex] = []
def addEdge(self, v1, v2):
self.E.append((v1, v2))
self.neighbours[v1].append(v2)
def addCost(self, edge, cost):
if edge in self.E:
self.cost[edge] = cost
def getCost(self, edge):
if edge in self.E:
return self.cost[edge]
def getNeighbors(self, vertex):
if vertex in self.V:
return self.neighbours[vertex]
def DijkstraShortestPath(self, start, goal):
Q = set()
distances = {}
prev = {}
for v in self.V:
distances[v] = float("inf")
prev[v] = None
Q.add((v[0], v[1]))
distances[start] = 0
while Q:
u = min(Q, key=distances.get)
if u == goal:
break
Q.remove(u)
for v in self.getNeighbors(u):
c = distances[u] + self.cost[(u,v)]
if c < distances[v]:
distances[v] = c
prev[v] = u
path = []
u = goal
while prev[u] != None:
path.append(u)
u = prev[u]
path.append(u)
return path[::-1]
def removeVertices(self, points):
for p in points:
if p in self.V:
self.V.remove(p)
for edge in self.E:
if p in edge:
self.E.remove(edge)