Exp 4
Exp 4
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)
graph = {
"A": ["B", "C", "G"],
"B": ["D", "E"],
"C": ["F"],
"G": ["H", "I"]
}
print(dfs(graph, "A"))
Output :
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)
print(bfs(graph, "A"))
Output :