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
| class Graph: def __init__(self,numVertices,directed=False): self.adjMatrix = [[[None] * numVertices] for _ in range(numVertices)] self.numVertices = numVertices self.vertices = [] self.directed = directed for i in range(0,numVertices): newVertex = Vertex(i) self.vertices.append(newVertex)
def addVertex(self,vtx,id): if(0<=vtx<self.numVertices): self.vertices[vtx].setVertexID(id)
def getVertex(self,n): for vertex in range(0,self.numVertices): if n == self.vertices[vertex].getVertexID(): return vertex return None def addEdge(self,frm,to,cost=0): if self.getVertex(frm)is not None and self.getVertex(to)is not None: self.adjMatrix[self.getVertex(frm)][self.getVertex(to)] = cost def getVertices(self): vertices = [] for vtx in range(0,self.numVertices): vertices.append(self.vertices[vtx].getVertexID()) return vertices
def printMatrix(self): for u in range(0,self.numVertices): row = [] for v in range(0,self.numVertices): if self.adjMatrix[u][v] is not None: row.append(str(self.adjMatrix[u][v])) else : '/' print(row)
def getEdges(self): edges = [] for u in range(0,self.numVertices): for v in range(0,self.numVertices): if self.adjMatrix[u][v] is not None : vID = self.vertices[u].getVertexID() wID = self.vertices[v].getVertexID() edges.append((vID,wID,self.adjMatrix[u][v])) return edges
def getNeighbors(self,n): neighbors = [] for vtx in range(0,self.numVertices): if n == self.vertices[vtx].getVertexID(): for neighbor in range(0,self.numVertices): if(self.adjMatrix[vtx][neighbor]is not None): neighbors.append(self.vertices[neighbor].getVertexID()) return neighbors
|