graph theory
shortest path
unweighted graph
BFS algorithm
pathfinding

Shortest path fewest nodes for unweighted graph

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Graph theory is a fundamental area of computer science and mathematics that deals with the study of graphs. A graph consists of vertices (or nodes) connected by edges. One of the common problems encountered in graph theory is finding the shortest path between two nodes. In the case of unweighted graphs, where each edge has the same "weight" or no weight, the shortest path is determined based on the fewest number of nodes or edges traversed.

Understanding Unweighted Graphs

In an unweighted graph, the focus is on the number of edges traversed rather than their cost. Therefore, the shortest path is defined by the path that includes the minimal number of edges between the start node and the destination node.

Key Characteristics:

  • Vertices (Nodes): Interconnected points in the graph.
  • Edges: The connections between the nodes, each edge considered equal in "weight."

Shortest Path Algorithms

For unweighted graphs, the most efficient algorithm to determine the shortest path is Breadth-First Search (BFS).

Breadth-First Search (BFS)

Breadth-First Search operates by exploring the closest nodes first before moving to the next level nodes. This characteristic makes BFS well-suited for finding the shortest path in unweighted graphs.

How BFS Works:

  1. Start at the Root Node: Begin at the source node.
  2. Explore Neighbors: Visit all the adjacent nodes (immediate neighbors).
  3. Use a Queue: Utilize a queue data structure to keep track of nodes to be explored.
  4. Mark Visited Nodes: Avoid revisiting nodes by marking them as visited.
  5. Continue Until Destination is Found: Repeat the process until the target node is reached.

BFS Pseudocode:

  • Cycle Handling: BFS naturally handles cycles by marking nodes as visited, preventing infinite loops.
  • Multiple Paths: In case of multiple shortest paths, BFS will find the first one it encounters.
  • Undirected vs. Directed Graphs: BFS applies to both, but care should be taken to follow direction in directed graphs.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.