22CD3014 Lab2
22CD3014 Lab2
BFS
graph = {
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
while queue:
return visited
# Example usage:
print("BFS:", bfs_result)
def dfs(graph, start):
while stack:
return visited
# Example usage:
print("DFS:", dfs_result)
OUPUT
graph = {
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
while stack:
return visited
# Example usage:
print("DFS:", dfs_result)
DFS Code (Using Recursion)
from collec ons import deque
graph = {
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
if visited is None:
visited = []
visited.append(node)
return visited
# Example usage:
graph = {
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
queue = deque([(start, [start])]) # Queue holds tuples of (current node, path to this node).
while queue:
node, path = queue.pople () # Dequeue a node along with the path to reach it.
# Example usage:
graph = {
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
def dfs_with_goal(graph, start, goal):
stack = [(start, [start])] # Stack holds tuples of (current node, path to this node).
while stack:
node, path = stack.pop() # Pop a node along with the path to reach it.
# Example usage:
graph = {
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
if visited is None:
visited = []
if path is None:
path = [node]
visited.append(node)
return result