-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs_graph.py
65 lines (43 loc) · 1.28 KB
/
bfs_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
#Python program to print BFS traversal
#from a given source vertex. BFS(int s)
#traverses vertices reachable from s.
from collections import defaultdict
#This class represents a directed graph
#using adjacency list representation
class Graph:
def __init__(self):
#default dictionary to store graph
self.graph=defaultdict(list)
#function to add edge to graph
def AddEdge(self,u,v):
self.graph[u].append(v)
#function to print a BFS of graph
def BFS(self,s):
#mark all vertices as not visited
visited=[False] * (max(self.graph) + 1)
#create queue for BFS
queue=[]
#Mark the source node as
#visited and enqueue it
queue.append(s)
visited[s] =True
while queue:
#Dequeue a vertex
#from queue and print it
s=queue.pop(0)
print(s,end=" ")
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
#Driver code
g = Graph()
g.AddEdge(0,1)
g.AddEdge(0,2)
g.AddEdge(1,2)
g.AddEdge(2,0)
g.AddEdge(2,3)
g.AddEdge(3,3)
print("the following is Breadth First traversal"
"(starting from vertex 2)")
g.BFS(2)