BFS Programs
BFS Programs
Search algorithms are fundamental tools in computer science for exploring graphs and trees.
Let me explain three important ones in simple terms.
Breadth-First Search (BFS)
What it is: BFS explores all nodes at the present "depth level" before moving on to nodes at
the next depth level.
How it works:
Starts at the root node (or any starting node)
Explores all neighboring nodes first
Then moves to the next level neighbors
Uses a queue (First-In-First-Out) to keep track of nodes
Real-life analogy: Imagine searching for your keys at home:
1. First check all rooms on the first floor
2. Then go upstairs and check all rooms there
3. Finally check the basement
When to use:
When you want to find the shortest path in an unweighted graph
When the solution is likely close to the starting point
Example: Finding the shortest path in a maze where all moves have equal cost.
Algorithm:
🔍 Use: Finds the shortest path in unweighted graphs.
def BFS(start):
queue = [start] # Use a queue to explore level by level
visited = set([start]) # Keep track of visited nodes
def UCS(start):
queue = [(0, start)] # Priority queue: (cost_so_far, node)
visited = set()
while queue:
cost, node = heapq.heappop(queue) # Node with the lowest cost
if node in visited:
continue # Skip if we've already processed it
visited.add(node)
print(node) # Process the node (could be checking goal)
Comparison Summary
Algorith
Order of Exploration Data Structure Best For
m