Data Structures and Algorithms (DSA)  

What is Graph Algorithms: BFS, DFS, and Shortest Path with Examples

Introduction

In the world of computer science and data structures, graphs are one of the most powerful tools for representing relationships between objects. However, graphs alone aren’t very useful without algorithms that allow us to explore and analyze them. That’s where Graph Traversal Algorithms like BFS (Breadth-First Search) and DFS (Depth-First Search) come into play. Additionally, algorithms such as Dijkstra’s Shortest Path Algorithm and Bellman-Ford Algorithm help us find the shortest routes between nodes.

What are Graph Traversal Algorithms?

Graph Traversal means visiting all the nodes in a graph exactly once in a systematic way. There are two primary traversal methods:

  1. Breadth-First Search (BFS) – explores neighbors level by level.

  2. Depth-First Search (DFS) – explores as far as possible down one path before backtracking.

These algorithms form the foundation for advanced techniques such as pathfinding, network analysis, and cycle detection.

Understanding BFS (Breadth-First Search)

BFS explores all neighbors of a node before moving to the next level. It uses a queue data structure (FIFO – First In, First Out).

Think of it as spreading outward from a starting point in waves, like ripples in water.

Example: Graph

A → B → C → D → E

BFS from A visits nodes level by level: A → B → C → D → E.

Python Implementation:

from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])

    while queue:
        node = queue.popleft()
        if node not in visited:
            print(node, end=' ')
            visited.add(node)
            for neighbor in graph[node]:
                if neighbor not in visited:
                    queue.append(neighbor)

# Example graph
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}

print("BFS Traversal:")
bfs(graph, 'A')

Output:

BFS Traversal:
A B C D E F

Time and Space Complexity:

  • Time: O(V + E)

  • Space: O(V)

Real-Life Uses of BFS:

  1. Shortest path in unweighted graphs (like finding the minimum steps in a maze).

  2. Web crawlers that explore pages level by level.

  3. Social networks – finding people within N degrees of connection.

  4. Broadcasting in computer networks.

Understanding DFS (Depth-First Search)

DFS explores as far as possible along one path before backtracking. It uses a stack (either explicitly or through recursion).

Think of DFS like exploring a maze: you keep moving forward until you hit a wall, then backtrack and try a new path.

Example: Graph

A → B → D
   → E → F

DFS from A visits nodes in depth order: A → B → D → E → F.

Python Implementation:

def dfs(graph, node, visited=None):
    if visited is None:
        visited = set()
    if node not in visited:
        print(node, end=' ')
        visited.add(node)
        for neighbor in graph[node]:
            dfs(graph, neighbor, visited)

# Example usage
print("\nDFS Traversal:")
dfs(graph, 'A')

Output:

DFS Traversal:
A B D E F C

Time and Space Complexity:

  • Time: O(V + E)

  • Space: O(V)

Real-Life Uses of DFS:

  1. Topological sorting (used in task scheduling).

  2. Cycle detection in directed and undirected graphs.

  3. Maze or puzzle solving.

  4. Pathfinding in AI and games.

  5. Connected components identification in networks.

BFS vs DFS: Comparison Table

FeatureBFS (Breadth-First Search)DFS (Depth-First Search)
Data StructureQueueStack / Recursion
Traversal OrderLevel by LevelDepth-wise
Memory UsageHigherLower
Suitable ForShortest path, level order traversalDeep exploration, cycle detection
CompletenessAlways finds the shortest pathMay not find the shortest path
Time ComplexityO(V + E)O(V + E)
Space ComplexityO(V)O(V)

Understanding Dijkstra’s Shortest Path Algorithm

Dijkstra’s Algorithm is a popular method for finding the shortest path between nodes in a weighted graph (non-negative weights).

It works by continuously picking the node with the smallest known distance and updating the distances of its neighbors.

Example: Consider this weighted graph

A → B (4), A → C (2)
B → C (5), B → D (10)
C → E (3), E → D (4)

The shortest path from A to D is A → C → E → D with a total cost of 9.

Python Implementation:

import heapq

def dijkstra(graph, start):
    pq = []  # priority queue
    heapq.heappush(pq, (0, start))
    distances = {node: float('inf') for node in graph}
    distances[start] = 0

    while pq:
        current_distance, current_node = heapq.heappop(pq)

        if current_distance > distances[current_node]:
            continue

        for neighbor, weight in graph[current_node].items():
            distance = current_distance + weight
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(pq, (distance, neighbor))

    return distances

# Example graph
graph = {
    'A': {'B': 4, 'C': 2},
    'B': {'C': 5, 'D': 10},
    'C': {'E': 3},
    'E': {'D': 4},
    'D': {}
}

print("\nShortest distances from A:")
print(dijkstra(graph, 'A'))

Output:

Shortest distances from A:
{'A': 0, 'B': 4, 'C': 2, 'E': 5, 'D': 9}

Time and Space Complexity:

  • Time: O((V + E) log V)

  • Space: O(V)

Real-Life Uses of Dijkstra’s Algorithm:

  1. GPS and Navigation Systems: Finding the shortest driving route.

  2. Network Routing Protocols: Used in OSPF (Open Shortest Path First).

  3. Flight Scheduling: Finding shortest or cheapest flight routes.

  4. Game Development: AI pathfinding between two points.

Other Shortest Path Algorithms

  1. Bellman-Ford Algorithm:

    • Works with negative edge weights.

    • Time Complexity: O(V * E).

    • Used in network routing algorithms that can handle cost adjustments.

  2. Floyd-Warshall Algorithm:

    • Finds shortest paths between all pairs of vertices.

    • Time Complexity: O(V³).

    • Used in traffic flow optimization and social network analysis.

Real-Life Applications of Graph Algorithms

  1. Social Media: Finding mutual friends or connection levels.

  2. Navigation Apps: Google Maps and GPS routing systems.

  3. Computer Networks: Packet routing using shortest path algorithms.

  4. AI and Gaming: Pathfinding for moving characters efficiently.

  5. Search Engines: Web crawlers explore interconnected web pages.

  6. Project Management: Dependency resolution and task scheduling using topological sort.

Summary

Graph algorithms such as BFS, DFS, and Dijkstra’s Shortest Path form the foundation for solving many real-world computational problems. BFS explores nodes level by level, making it ideal for shortest paths in unweighted graphs, while DFS explores depth-first, useful for cycle detection and deep search. Dijkstra’s Algorithm efficiently finds the shortest path in weighted graphs and is widely used in navigation, network routing, and game development. Mastering these algorithms helps developers solve complex problems involving connectivity, optimization, and exploration — making them essential tools in computer science.