Exploring Variants of BFS Algorithms: A Comprehensive Guide

Namrata
5 min readFeb 27, 2024

--

BFS is a widely used algorithm, and its versatility is evident in various problem-solving scenarios. In this article, we’ll delve into different variants of BFS and how they can be applied to solve specific problems. Feel free to drop a comment if you think anything is missing, and don’t forget to upvote if you find this guide helpful.

1. Standard BFS

Standard BFS involves using a queue to explore nodes level by level until the queue is empty. It is the foundational form of BFS and is known for its ability to find the shortest path.

Why BFS always finds the shortest path: The first time a node is discovered, its distance from the root node will always be the shortest. This principle applies recursively to all undiscovered nodes.

Example Problem: Find if Path Exists in a Graph

2. BFS from Borders

In contrast to the conventional BFS methodology, which often commences from a central node, BFS from Borders embraces a unique starting point — the edges of the grid. This strategic initiation introduces a fresh perspective to exploration, tapping into information residing on the periphery before delving into the core of the problem.

Real-Life Analogy: Exploring New Territories

Consider a scenario akin to exploring a new territory. Instead of starting from the centre, the expedition strategically begins from the outer edges, gradually uncovering the intricacies of the uncharted land.

Implementation Strategy

To harness the potential of BFS from Borders, follow these steps:

  1. Identify Grid Borders: Determine the edges of the grid, considering parameters like row=0, m-1, column=0, and n-1.
  2. Queue Initialization: Populate the BFS queue with nodes from the identified border positions.
  3. Strategic Exploration: Commence BFS traversal from the border nodes, gradually progressing towards the grid’s interior.
  4. Insightful Optimization: Leverage information gained from border exploration to optimize the problem-solving process.

Example problems:
130. Surrounded Regions
417. Pacific Atlantic Water Flow

3. 0–1 BFS

A specialized technique emerges — 0–1 BFS. Unlike standard BFS, where traversal progresses uniformly, 0–1 BFS prioritizes paths with a cost/value of 0 over those with a value of 1. This optimization proves invaluable in scenarios where efficiency is paramount. To facilitate this preference, a deque (double-ended queue) is employed instead of a traditional queue. Nodes with a cost/value of 0 are inserted at the front of the deque, while those with a value of 1 are inserted at the back. Let’s delve into the intricacies of 0–1 BFS and unlock its potential for efficient pathfinding.

Real-Life Analogy: Border Patrol

Consider a scenario akin to navigating through traffic lanes. In standard BFS, all vehicles progress uniformly through the lanes. However, 0–1 BFS introduces a fast lane exclusively for vehicles with zero cost, expediting their journey while maintaining the flow of other vehicles in the regular lane.

Implementation in Problem-Solving

To harness the efficiency of 0–1 BFS effectively, follow these steps:

  1. Deque Initialization: Initialize a deque to facilitate traversal, accommodating nodes with different cost/values.
  2. Priority Insertion: Insert nodes with a cost/value of 0 at the front of the deque, prioritizing their exploration. Nodes with a value of 1 are inserted at the back, ensuring their traversal in due course.
  3. Optimized Traversal: Proceed with BFS traversal, leveraging the deque’s prioritized insertion to explore paths efficiently.

Example problems:
Shortest Bridge — LeetCode
Minimum Cost to Make at Least One Valid Path in a Grid — LeetCode
Minimum Obstacle Removal to Reach Corner — LeetCode

4. BFS with Bitmasking

In standard BFS scenarios, a visited array or set is diligently maintained to steer clear of revisiting nodes. However, BFS with Bitmasking challenges this norm. Nodes, instead of being dismissed, are revisited, now equipped with an additional layer of information — the state. This state, often represented by a bitmask, augments the node’s identity, enriching the exploration process.

Real-Life Analogy: Dynamic Information Gathering

Imagine a scenario where explorers traverse a grid, marking their path not only with location identifiers but also with dynamically changing information. This dynamic information, akin to the state in BFS with Bitmasking, enhances their understanding of the terrain.

Implementation Strategy

  1. Bitmask Integration: Incorporate a bitmask into the visited status of each node during BFS traversal.
  2. State Dynamics: Understand the changing states as nodes are revisited, allowing for dynamic adaptation during exploration.
  3. Alternative Approaches: Be open to exploring alternative solutions, such as DFS + Bitmasking + memoization, when tackling problems suited for BFS with Bitmasking.

5. Bi-directional BFS (Bi-BFS)

This innovative approach takes efficiency to new heights by initiating traversal simultaneously from both the source and target. Through alternating moves, the algorithm strategically progresses until a common node is processed in both directions, effectively reducing search time. The advantages of Bi-BFS extend beyond its efficiency, presenting applications to other algorithms such as Dijkstra (directed or undirected) and directed graphs (unweighted). Let’s explore the advantages, applications, and the versatility of Bi-BFS in tackling a wide array of problems.

Real-Life Analogy: Dual Expedition for Efficiency

Imagine an expedition exploring a vast landscape. Instead of deploying a single team from a central location, two teams embark from opposite ends. They strategically navigate, meeting at a common point, effectively reducing the time and resources required for exploration. Bi-BFS mirrors this efficiency in algorithmic exploration.

Implementation Strategy

To harness the power of Bi-BFS effectively, follow these steps:

  1. Initiate Both Ends: Start BFS simultaneously from both the source and target nodes.
  2. Alternating Moves: Progress through alternating moves, ensuring that both directions are explored in tandem.
  3. Common Node Check: Conclude the search when a common node is processed in both directions.
  4. In conclusion, understanding these BFS variants equips you with powerful tools for tackling diverse problem-solving scenarios. Feel free to explore these techniques and apply them to your problem-solving toolkit.

6. Multi-Source BFS

In standard BFS, we set forth from a solitary source node and progressively unravel the maze of possibilities. The paradigm shift in Multi-Source BFS lies in the presence of several source nodes, each holding significance. These sources could represent cities, points of interest, or entities with distinct characteristics.

Real-Life Analogy: Police Stations in Cities

Consider a map with multiple cities, some boasting police stations. The task is to determine the nearest police station for every city. This real-life analogy captures the essence of Multi-Source BFS. By initiating the BFS algorithm from all police stations simultaneously, we efficiently ascertain the closest police station for each city. The beauty of this approach is that the moment we reach a city from a police station, we can confidently declare it as the nearest one.

Implementation Strategy

  1. Initialization: Place all the source nodes (in this case, cities or potential destinations) into the BFS queue.
  2. BFS Exploration: Commence the BFS exploration from each source node simultaneously. The algorithm dynamically unfolds the distances, gradually revealing the proximity of each city to its nearest police station.
  3. Termination: As soon as a city is reached from a police station during the BFS traversal, mark it as the nearest one. The algorithm continues until all cities have been visited, ensuring that each city is associated with its closest police station.

In conclusion, understanding these BFS variants equips you with powerful tools for tackling diverse problem-solving scenarios. Feel free to explore these techniques and apply them to your problem-solving toolkit.

Happy coding!

--

--

Namrata

Engineering @Microsoft. A software developer writing her daily bits of work Coding