Shortest Path in Unweighted Graph (Breadth-First Search - BFS)

beginner
22 min

Shortest Path in Unweighted Graph (Breadth-First Search - BFS)

Welcome to our comprehensive guide on finding the shortest path in an unweighted graph using Breadth-First Search (BFS)! šŸŽÆ

In this lesson, we'll explore:

  1. What is a graph?
  2. What is an unweighted graph?
  3. Understanding Breadth-First Search (BFS)
  4. Implementing BFS in Python
  5. Real-world applications of BFS
  6. Quiz

Let's dive in!

What is a graph? šŸ“

A graph is a collection of nodes (also called vertices) and edges that connect these nodes. Each edge represents a connection between two nodes.

What is an unweighted graph? šŸ“

An unweighted graph is a specific type of graph where the edges do not have any associated weights. In other words, all edges have the same weight, usually 1.

Understanding Breadth-First Search (BFS) šŸ’”

BFS is a popular algorithm used to traverse or search through a graph, ensuring that nodes are visited in a breadthwise manner. It starts at the root node and explores all the nodes at the current depth level before moving to the next level. This is particularly useful in finding the shortest path between nodes in an unweighted graph.

Implementing BFS in Python šŸ“

Here's a simple BFS implementation in Python for an unweighted graph. We'll use an adjacency list for convenience.

python
def bfs(graph, start): visited = set() queue = [(start, [start])] while queue: (node, path) = queue.pop(0) if node not in visited: visited.add(node) for neighbor in graph[node]: if neighbor not in visited: queue.append((neighbor, path + [neighbor])) return visited

šŸ’” Pro Tip: Use a dictionary to represent the graph with nodes as keys and lists of their neighbors as values.

Real-world applications of BFS šŸ“

BFS is used in various real-world scenarios, such as:

  1. Network routing
  2. Image segmentation
  3. Find shortest routes in GPS navigation systems
  4. Solving the 8-Queens puzzle

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

Which of the following is a type of graph where all edges have the same weight?