MCPcopy Create free account
hub / github.com/subbarayudu-j/TheAlgorithms-Python / Graph

Class Graph

Graphs/breadth_first_search.py:9–46  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7
8
9class Graph():
10 def __init__(self):
11 self.vertex = {}
12
13 # for printing the Graph vertexes
14 def printGraph(self):
15 for i in self.vertex.keys():
16 print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]]))
17
18 # for adding the edge beween two vertexes
19 def addEdge(self, fromVertex, toVertex):
20 # check if vertex is already present,
21 if fromVertex in self.vertex.keys():
22 self.vertex[fromVertex].append(toVertex)
23 else:
24 # else make a new vertex
25 self.vertex[fromVertex] = [toVertex]
26
27 def BFS(self, startVertex):
28 # Take a list for stoting already visited vertexes
29 visited = [False] * len(self.vertex)
30
31 # create a list to store all the vertexes for BFS
32 queue = []
33
34 # mark the source node as visited and enqueue it
35 visited[startVertex] = True
36 queue.append(startVertex)
37
38 while queue:
39 startVertex = queue.pop(0)
40 print(startVertex, end = ' ')
41
42 # mark all adjacent nodes as visited and print them
43 for i in self.vertex[startVertex]:
44 if visited[i] == False:
45 queue.append(i)
46 visited[i] = True
47
48if __name__ == '__main__':
49 g = Graph()

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected