DFS & BFS in graph

This commit is contained in:
AnupKumarPanwar 2017-07-18 16:17:48 +05:30
parent 325deda07c
commit 37705510e5
2 changed files with 54 additions and 65 deletions

View File

@ -1,45 +1,35 @@
class Graph:
class GRAPH:
"""docstring for GRAPH"""
def __init__(self, nodes):
self.nodes=nodes
self.graph=[[0]*nodes for i in range (nodes)]
self.visited=[0]*nodes
def __init__(self, vertex):
self.vertex = vertex
self.graph = [[0] * vertex for i in range(vertex) ]
def add_edge(self, u, v):
self.graph[u - 1][v - 1] = 1
self.graph[v - 1][u - 1] = 1
def show(self):
print self.graph
for i in self.graph:
for j in i:
print(j, end=' ')
print(' ')
def bfs(self,v):
def add_edge(self, i, j):
self.graph[i][j]=1
self.graph[j][i]=1
visited = [False]*self.vertex
visited[v - 1] = True
print('%d visited' % (v))
def bfs(self,s):
queue=[s]
while len(queue)!=0:
x=queue.pop(0)
print(x)
self.visited[x]=1
for i in range(0,self.nodes):
if self.graph[x][i]==1 and self.visited[i]==0:
queue.append(i)
self.visited[i]=1
queue = [v - 1]
while len(queue) > 0:
v = queue[0]
for u in range(self.vertex):
if self.graph[v][u] == 1:
if visited[u]== False:
visited[u] = True
queue.append(u)
print('%d visited' % (u +1))
queue.pop(0)
g = Graph(10)
g.add_edge(1,2)
g.add_edge(1,3)
g.add_edge(1,4)
g.add_edge(2,5)
g.add_edge(3,6)
g.add_edge(3,7)
g.add_edge(4,8)
g.add_edge(5,9)
g.add_edge(6,10)
g.bfs(1)
n=int(input("Enter the number of Nodes : "))
g=GRAPH(n)
e=int(input("Enter the no of edges : "))
print("Enter the edges (u v)")
for i in range(0,e):
u,v=map(int, raw_input().split())
g.add_edge(u,v)
s=int(input("Enter the source node :"))
g.bfs(s)

View File

@ -1,33 +1,32 @@
class Graph:
class GRAPH:
"""docstring for GRAPH"""
def __init__(self, nodes):
self.nodes=nodes
self.graph=[[0]*nodes for i in range (nodes)]
self.visited=[0]*nodes
def __init__(self, vertex):
self.vertex = vertex
self.graph = [[0] * vertex for i in range(vertex) ]
self.visited = [False] * vertex
def add_edge(self, u, v):
self.graph[u - 1][v - 1] = 1
self.graph[v - 1][u - 1] = 1
def show(self):
print self.graph
for i in self.graph:
for j in i:
print(j, end=' ')
print(' ')
def add_edge(self, i, j):
self.graph[i][j]=1
self.graph[j][i]=1
def dfs(self, u):
self.visited[u - 1] = True
print('%d visited' % u)
for i in range(1, self.vertex + 1):
if self.graph[u - 1][i - 1] == 1 and self.visited[i - 1] == False:
def dfs(self,s):
self.visited[s]=1
print(s)
for i in range(0,self.nodes):
if self.visited[i]==0 and self.graph[s][i]==1:
self.dfs(i)
g = Graph(5)
g.add_edge(1,4)
g.add_edge(4,2)
g.add_edge(4,5)
g.add_edge(2,5)
g.add_edge(5,3)
g.dfs(1)
n=int(input("Enter the number of Nodes : "))
g=GRAPH(n)
e=int(input("Enter the no of edges : "))
print("Enter the edges (u v)")
for i in range(0,e):
u,v=map(int, raw_input().split())
g.add_edge(u,v)
s=int(input("Enter the source node :"))
g.dfs(s)