0% found this document useful (0 votes)
11 views3 pages

Exp 4

exp 4 of A.I for MU
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views3 pages

Exp 4

exp 4 of A.I for MU
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Experiment 4

Implementation of DFS and BFS search technique.

1 ) DFS (Depth First Search) :


Code :
def dfs(graph, source):
path = []
stack_val = [source]

while len(stack_val) != 0:
s = stack_val.pop()
if s not in path:
path.append(s)
if s not in graph:
continue
for node in graph[s]:
if node not in path:
stack_val.append(node)

return " ".join(path)

graph = {
"A": ["B", "C", "G"],
"B": ["D", "E"],
"C": ["F"],
"G": ["H", "I"]
}
print(dfs(graph, "A"))
Output :

2 ) BFS (Breadth First Search)

Code :
def bfs(graph, source):
path = []
queue_val = [source]

while len(queue_val) != 0:
s = queue_val.pop(0)
if s not in path:
path.append(s)
if s not in graph:
continue
for node in graph[s]:
if node not in path:
queue_val.append(node)

return " ".join(path)


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

print(bfs(graph, "A"))

Output :

You might also like