0% found this document useful (0 votes)
17 views1 page

BFS DFS

Uploaded by

Ishaan Mattoo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views1 page

BFS DFS

Uploaded by

Ishaan Mattoo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#BFS

graph = {
'A': ['B', 'C', "D"],
'B': ['E', "F"],
'C': ['G', "H"],
'D': ["H"],
'E': [],
"F": [],
'G': [],
"H": [],
'I': []
}

def bfs(visit_complete, graph, current_node):


visit_complete.append(current_node)
queue = []
queue.append(current_node)

while queue:
s = queue.pop(0)
print(s)

for neighbour in graph[s]:


if neighbour not in visit_complete:
visit_complete.append(neighbour)
queue.append(neighbour)
bfs([], graph, 'A')

#Output: A B C D E F G H I

#DFS
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)

print(start)

for next in graph[start] - visited:


dfs(graph, next, visited)
return visited

#adjacency list
graph = {'0': set(['1', '2']),
'1': set(['0', '3', '4']),
'2': set(['0']),
'3': set(['1']),
'4': set(['2', '3'])}

dfs(graph, '0')

#Output: 0 2 1 3 4

You might also like