-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.py
81 lines (57 loc) · 1.72 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
67
68
69
70
71
72
73
74
75
76
77
78
class Vertex:
def __init__(self,key):
self.ID = key
self.connectedTo = {}
self.predecessor = None
self.color = 'white'
self.distance = 0
def addNeighbor(self,nbr,weight=0):
self.connectedTo[nbr] = weight
def __str__(self):
return str(self.ID) + 'connected to' + str([x.id for x in self.connectedTo])
def getConnections(self):
return self.connectedTo.keys()
def getID(self):
return self.ID
def getWeight(self,nbr):
return self.connectedTo[nbr]
def getDistance(self):
return self.distance
def setDistance(self,d):
self.distance = d
def setPred(self,v):
self.predecessor = v
def getPred(self):
return self.predecessor
def getColor(self):
return self.color
def setColor(self,color):
self.color = color
class Graph:
def __init__(self):
self.vertList = {}
self.numVertices = 0
def addVertex(self,key):
self.numVertices += 1
newVertex=Vertex(key)
self.vertList[key] = newVertex
return newVertex
def getVertex(self,n):
if n in self.vertList:
return self.vertList[n]
else:
return None
def __contains__(self, n):
return n in self.vertList
def addEdge(self,f,t,cost=0):
if f not in self.vertList:
_ = self.addVertex(f)
if t not in self.vertList:
_ = self.addVertex(t)
self.vertList[f].addNeighbor(self.vertList[t],cost)
def getVertices(self):
return self.vertList.keys()
def __iter__(self):
return iter(self.vertList.values())
def getConnections(self):
return self.vertList