from collections import deque
def bfs(graph, start):
visited = set() # Track visited nodes
queue = deque([start]) # Use a queue to explore nodes level by level
result = [] # Store the order of the nodes
while queue:
node = [Link]() # Dequeue a node
if node not in visited:
[Link](node) # Mark node as visited
[Link](node) # Record the node in the result
# Add only unvisited neighbors to the queue
for neighbor in graph[node]:
if neighbor not in visited:
[Link](neighbor)
return result
# Example usage
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
print(bfs(graph, 'A')) # Expected output: ['A', 'B', 'C', 'D', 'E', 'F']
#BFS CODE
def dfs_iterative(graph, start):
visited = set() # Track visited nodes
stack = [start] # Use a stack for LIFO order
result = [] # Store the order of the nodes
while stack:
node = [Link]() # Pop a node from the stack
if node not in visited:
[Link](node) # Mark node as visited
[Link](node) # Record the node in the result
# Add neighbors in reverse order to maintain correct DFS order
for neighbor in reversed(graph[node]):
if neighbor not in visited:
[Link](neighbor)
return result
# Example usage
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
print(dfs_iterative(graph, 'A')) # Expected output: ['A', 'B', 'D', 'E',
'F', 'C']
#DFS CODE