Python/Graphs/Breadth_First_Search.py

44 lines
1.0 KiB
Python
Raw Normal View History

2017-07-18 16:17:48 +05:30
class GRAPH:
"""docstring for GRAPH"""
2017-07-18 16:17:48 +05:30
def __init__(self, nodes):
self.nodes=nodes
self.graph=[[0]*nodes for i in range (nodes)]
self.visited=[0]*nodes
self.vertex = nodes
2017-06-22 20:15:03 -03:00
def bfs(self,v):
visited = [False]*self.vertex
visited[v] = True
queue = [v]
2017-06-22 20:15:03 -03:00
while len(queue) > 0:
v = queue[0]
print('%d,' %v,end='')
queue.pop(0)
2017-06-22 20:15:03 -03:00
for u in range(self.vertex):
if self.graph[v][u] == 1:
if visited[u]== False:
visited[u] = True
queue.append(u)
2017-07-18 16:17:48 +05:30
def add_edge(self, i, j):
self.graph[i][j]=1
n=int(input("Enter the number of Nodes : "))
g=GRAPH(n)
g.vertex = n
2017-07-18 16:17:48 +05:30
e=int(input("Enter the no of edges : "))
print("Enter the edges (u v)")
for i in range(0,e):
u,v=map(int,input().split())
2017-07-18 16:17:48 +05:30
g.add_edge(u,v)
s=int(input("Enter the source node : "))
print("BFS order:")
2017-07-18 16:17:48 +05:30
g.bfs(s)
print("")