Untitled
unknown
plain_text
a year ago
1.4 kB
10
Indexable
Best First Search
def bfs(graph, start_node):
queue = [start_node] # Use a list as a queue
visited = [] # Keep track of visited nodes
while queue:
current_node = queue.pop(0) # Remove the first node from the queue
if current_node not in visited:
visited.append(current_node) # Mark the node as visited
queue.extend(graph[current_node]) # Add neighbors to the queue
print("BFS Traversal:", visited)
# Example graph
graph = {
'P': ['Q', 'R'],
'Q': ['S', 'T'],
'R': ['U', 'V'],
'S': [],
'T': [],
'U': [],
'V': []
}
# Start BFS from node 'A'
bfs(graph, 'P')
Depth First Search
def dfs(graph, start_node, visited=None):
if visited is None:
visited = [] # Initialize the visited list for the first call
visited.append(start_node) # Mark the current node as visited
print(start_node, end=" ") # Print the visited node
# Recursively visit all unvisited neighbors
for neighbor in graph[start_node]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
# Example graph
graph = {
'P': ['Q', 'R'],
'Q': ['S', 'T'],
'R': ['U', 'V'],
'S': [],
'T': [],
'U': [],
'V': []
}
# Start DFS from node 'P'
print("DFS Traversal:")
dfs(graph, 'P')
Editor is loading...
Leave a Comment