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): def show(self):
print self.graph
for i in self.graph: def add_edge(self, i, j):
for j in i: self.graph[i][j]=1
print(j, end=' ') self.graph[j][i]=1
print(' ')
def bfs(self,v):
visited = [False]*self.vertex def bfs(self,s):
visited[v - 1] = True queue=[s]
print('%d visited' % (v)) 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] n=int(input("Enter the number of Nodes : "))
while len(queue) > 0: g=GRAPH(n)
v = queue[0] e=int(input("Enter the no of edges : "))
for u in range(self.vertex): print("Enter the edges (u v)")
if self.graph[v][u] == 1: for i in range(0,e):
if visited[u]== False: u,v=map(int, raw_input().split())
visited[u] = True g.add_edge(u,v)
queue.append(u) s=int(input("Enter the source node :"))
print('%d visited' % (u +1)) g.bfs(s)
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)

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