Graph Traversal Algorithms: BFS and DFS

Authors: - Dorothy Gale, Department of Computer Science, Emerald City Technical Institute - Huckleberry Finn, Department of Computer Science, Emerald City Technical Institute

Date: January 5, 2025

Abstract

Graph traversal algorithms systematically visit vertices in a graph. This paper examines the two fundamental approaches: Breadth-First Search—BFS—explores level-by-level, while Depth-First Search—DFS—explores as deep as possible before backtracking. Understanding their distinct characteristics is essential for selecting the appropriate algorithm for path-finding, connectivity analysis, and graph-based problem solving.

Example scroll made with Jupyter Notebook for Scroll Press.

Graph Fundamentals

A graph \(G = (V, E)\) consists of vertices \(V\) and edges \(E\) connecting pairs of vertices. Graph traversal visits all vertices systematically—a fundamental operation with applications in navigation, network analysis, web crawling, and game AI.

Key Insight: The choice between BFS and DFS fundamentally determines the order in which vertices are discovered, which impacts algorithm behavior in path-finding, cycle detection, and connectivity analysis.

The key difference between BFS and DFS lies in their exploration strategy:

  • BFS — Explores neighbors level by level using a queue
  • DFS — Explores as deeply as possible first using a stack or recursion

Comparative Analysis

When to Use BFS vs DFS

The table below summarizes the key decision factors:

Criterion BFS DFS
Shortest path — unweighted ✓ Optimal ✗ Not guaranteed
Memory efficiency — deep graphs ✗ High memory ✓ Lower memory
Completeness — infinite graphs ✓ Complete ✗ May get stuck
Cycle detection Possible ✓ Natural
Topological sorting Not applicable ✓ Natural
Path exists checking Either works Either works

⚠️ Infinite Graphs: DFS can get stuck exploring an infinite branch and never backtrack to find the goal. BFS will eventually find any reachable goal at finite depth.

Example: Social Network Analysis

Consider finding the connection between two users in a social network:

def find_connection_bfs(graph, start, target):
    """Find shortest path between two users using BFS."""
    if start == target:
        return [start]

    visited = {start}
    queue = deque([(start, [start])])

    while queue:
        vertex, path = queue.popleft()

        for neighbor in graph[vertex]:
            if neighbor == target:
                return path + [neighbor]

            if neighbor not in visited:
                visited.add(neighbor)
                queue.append((neighbor, path + [neighbor]))

    return None  # No connection exists

# Example: Finding connection between users
social_network = {
    'Alice': ['Bob', 'Charlie'],
    'Bob': ['Alice', 'David', 'Eve'],
    'Charlie': ['Alice', 'Frank'],
    'David': ['Bob'],
    'Eve': ['Bob', 'Frank'],
    'Frank': ['Charlie', 'Eve']
}

path = find_connection_bfs(social_network, 'Alice', 'Frank')
if path:
    print(f"Connection found: {' → '.join(path)}")
    print(f"Degrees of separation: {len(path) - 1}")

Note: BFS guarantees finding the shortest path—minimum degrees of separation—which is why LinkedIn and Facebook use BFS-based algorithms for “mutual connections” features.

Advanced Topics

Weighted Graphs

For graphs with weighted edges, neither BFS nor DFS guarantees optimal paths. Dijkstra’s algorithm—a weighted variant of BFS using a priority queue—or A* search are required.

Conclusion

BFS and DFS represent fundamental graph traversal strategies with complementary strengths. BFS excels at finding shortest paths and works well for shallow, wide graphs, while DFS is memory-efficient for deep graphs and naturally supports cycle detection and topological sorting. Understanding when to apply each algorithm is essential for effective algorithm design.

Key takeaway: The choice between BFS and DFS depends on problem requirements (shortest path vs memory efficiency), graph structure (wide vs deep), and desired properties (completeness, cycle detection).

References

  1. Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2022). Introduction to Algorithms, 4th ed. MIT Press.
  2. Sedgewick, R., & Wayne, K. (2011). Algorithms, 4th ed. Addison-Wesley.
  3. Skiena, S. S. (2020). The Algorithm Design Manual, 3rd ed. Springer.

Example scroll made with Jupyter Notebook for Scroll Press.