Skip to content

Commit

Permalink
clean up;simplify
Browse files Browse the repository at this point in the history
  • Loading branch information
harishvc committed Aug 24, 2018
1 parent 14f810e commit 2141c7a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 40 deletions.
36 changes: 15 additions & 21 deletions graph-traversal-bfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,17 @@
'''

import queue
def BFT(graph,start,end):
q = queue.Queue()
#Store node and path
q.put([start,start])
#Keep track of visited nodes
visited = []
while not q.empty():
#get node and path from the queue
nextNode,path = q.get()
#Found path!
if nextNode == end:
yield path
else:
#Visit all the edges of nextNone
visited.append(nextNode)
for node in graph[nextNode]:
#node has been visited?
if node not in visited:
#Store node and path
q.put([node,path+node])
def BFT(graph,traversed_nodes,visited,target):
while not traversed_nodes.empty():
current = traversed_nodes.get()
current_node,current_path = current[0],current[1]
if current_node == target:
yield current_path
elif current_node not in visited:
visited.append(current_node)
for node in graph[current_node]:
traversed_nodes.put([node,current_path+node])



#Adjacency list
Expand All @@ -53,5 +44,8 @@ def BFT(graph,start,end):

start = 'A'
end = 'F'
for path in BFT(graph,start,end):
q = queue.Queue()
q.put([start,start])
for path in BFT(graph,q,[],end):
print("->".join(path))

32 changes: 13 additions & 19 deletions graph-traversal-dfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,18 @@
'''

#Depth First Traversal
def DFT(graph,ConnectedNodes,end,visited,path):
for ConnectedNode in ConnectedNodes:
if ConnectedNode not in visited:
#Append current node to visited
visited.append(ConnectedNode)
#Append current node to path
path.append(ConnectedNode)
#Found path!
if ConnectedNode == end:
yield path
else:
#continue
yield from DFT(graph,graph[ConnectedNode],end,visited,path)
#pop current node from visited
visited.pop()
#pop current node from path
def DFT(graph,current,visited,target,path):
for node in graph[current]:
if node == target:
path.append(node)
yield path
path.pop()

elif node not in visited:
visited.append(node)
path.append(node)
yield from DFT(graph,node,visited,target,path)
path.pop()
visited.pop()

#Adjacency list
graph = {'A': ['B', 'C'],
Expand All @@ -48,5 +42,5 @@ def DFT(graph,ConnectedNodes,end,visited,path):
start = 'A'
end = 'F'

for path in DFT(graph,graph[start],end,[start],[start]):
print("->".join(path))
for path in DFT(graph,start,[start],end,[start]):
print("->".join(path))

0 comments on commit 2141c7a

Please sign in to comment.