Welcome to our deep dive into Breadth First Search (BFS)! In this lesson, we'll explore this essential algorithm used in graph traversal, learn its working, and understand its practical applications. Let's get started! šÆ
BFS is a graph traversal algorithm that explores all the vertices of a graph in a breadth-wise manner. It starts by visiting the vertex that is at the shortest distance from the starting vertex, then moves to the adjacent vertices that are at the same distance, and continues until it has explored all the vertices in the graph. š
BFS is primarily used to find the shortest path between two vertices in an unweighted graph or the shortest path from a single source vertex in a weighted graph. It also helps in checking if there is a path between two vertices in a graph. š”
Here's a simple implementation of BFS in Python for an unweighted graph:
def bfs(vertex, graph):
visited = [False] * len(graph)
queue = [vertex]
parent = [-1] * len(graph)
while queue:
current = queue.pop(0)
if not visited[current]:
visited[current] = True
for neighbor in graph[current]:
if not visited[neighbor]:
queue.append(neighbor)
parent[neighbor] = current
return parentFor a weighted graph, we'll maintain a distance array along with the parent array:
def bfs(source, graph, n):
visited = [False] * n
distance = [float('inf')] * n
parent = [-1] * n
queue = [(source, 0)]
while queue:
(current, dist) = queue.pop(0)
if not visited[current]:
visited[current] = True
distance[current] = dist
for neighbor in graph[current]:
if not visited[neighbor]:
queue.append((neighbor, dist + 1))
parent[neighbor] = current
return parent, distanceBFS can be applied to various real-world problems, such as:
Which graph traversal algorithm is used when we want to find the shortest path between two vertices in an unweighted graph?
That's all for today's lesson on BFS! With this knowledge, you're one step closer to becoming a proficient programmer. Stay tuned for more engaging and informative content on data structures and algorithms here at CodeYourCraft! š
Happy coding! š»š