Opening your learning path
Progress is saved as you study.
Opening your learning path
Progress is saved as you study.
The Graph BFS - Connected Components / Island Counting pattern applies when you need the Graph BFS - Connected Components / Island Counting technique within the Graph Traversal Patterns (DFS & BFS) pattern. Its time complexity is O(V + E) and space complexity O(V). It is used in 5 problems on Thita, including 01 Matrix, Rotting Oranges and Shortest Path in Binary Matrix. Common variations are Graph DFS - Cycle Detection (Directed Graph) and Deep Copy / Cloning.
Use BFS for shortest path in unweighted graphs. Solve word ladder, rotting oranges, and matrix problems.
Graph BFS - Connected Components / Island Counting is one of the 12 subpatterns of the Graph Traversal Patterns (DFS & BFS) pattern, which covers dFS/BFS traversal, topological sort, shortest paths, Union-Find, and MST. The whole pattern is about 5 hours of study. This subpattern is a core technique: expect it to come up directly in interviews.
Master graph algorithms including DFS/BFS traversal, topological sort, shortest paths (Dijkstra, Bellman-Ford), Union-Find, and advanced graph concepts. Problems in this subpattern are usually searched for as word ladder, rotting oranges, shortest path grid, BFS graph, leetcode 127, leetcode 994.
Read the theory for Graph BFS - Connected Components / Island Counting, then work the problems attached to it in the browser editor. Your solution runs against the problem's test cases, and the AI coach offers a hint about the technique you are missing rather than a finished solution. Progress is tracked per subpattern, so the Graph Traversal Patterns (DFS & BFS) tracker shows this one as covered once you have solved its problems.
Graph BFS - Connected Components / Island Counting is one lesson in a 16-pattern DSA course. If you are preparing end to end, work the interview-critical patterns first and use the pattern sheet as the checklist; if you are here for one technique, the Graph Traversal Patterns (DFS & BFS) guide is the shortest path back to the rest of it.
Imagine you’re in a city after a heavy snowstorm. Some roads are blocked, and you want to find out which neighborhoods are still connected by open roads. You could start at one house, walk to all reachable houses, and mark them as “visited.” Then, you pick another unvisited house and repeat. Each time, you discover a new “connected component”—a cluster of places you can reach without crossing blocked roads.
This is the essence of the Connected Components / Island Counting subpattern using Breadth-First Search (BFS) in graphs. In programming, we often represent cities, islands, or even word transformations as graphs. BFS helps us systematically explore all nodes (or cells, or words) connected together, one layer at a time—like ripples spreading out from a stone dropped in a pond.
This pattern is super useful when you need to:
Everyday analogy: Think of BFS as organizing a neighborhood block party. You start with one house, invite all its immediate neighbors, then ask those neighbors to invite their neighbors, and so on—ensuring no one is missed and everyone is reached in the shortest number of steps.
Let’s break down the key ideas behind this subpattern:
Let’s build a mental model for tackling these problems:
Visualize the Problem as a Graph
Identify What Needs to Be Explored
Set Up Visited Tracking
Use a Queue for BFS
Handle Edge Cases
Let’s walk through a BFS implementation for the “Rotting Oranges” problem.
1#include <vector>
2#include <queue>
3using namespace std;
4
5// Function to compute the minimum minutes to rot all oranges
6int orangesRotting(vector<vector<int>>& grid) {
7 int rows = grid.size();
8 int cols = grid[0].size();
9 queue<pair<int, int>> q; // Queue for BFS: stores positions of rotten oranges
10 int freshCount = 0; // Count of fresh oranges
11
12 // Step 1: Initialize the queue with all initially rotten oranges
13 for (int r = 0; r < rows; ++r) {
14 for (int c = 0; c < cols; ++c) {
15 if (grid[r][c] == 2) {
16 q.push({r, c}); // Rotten orange found
17 } else if (grid[r][c] == 1) {
18 ++freshCount; // Count fresh oranges
19 }
20 }
21 }
22
23 // Directions for 4-adjacent cells (up, down, left, right)
24 vector<pair<int, int>> directions = {{-1,0},{1,0},{0,-1},{0,1}};
25 int minutes = 0;
26
27 // Step 2: BFS to rot adjacent fresh oranges minute by minute
28 while (!q.empty() && freshCount > 0) {
29 int size = q.size(); // Number of oranges to process this minute
30 for (int i = 0; i < size; ++i) {
31 auto [r, c] = q.front(); q.pop();
32 // Check all 4 directions
33 for (auto [dr, dc] : directions) {
34 int nr = r + dr, nc = c + dc;
35 // If neighbor is in bounds and is a fresh orange
36 if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1) {
37 grid[nr][nc] = 2; // Rot the orange
38 --freshCount; // One less fresh orange
39 q.push({nr, nc}); // Add to queue for next minute
40 }
41 }
42 }
43 ++minutes; // One minute passed
44 }
45
46 // If there are fresh oranges left, return -1
47 return freshCount == 0 ? minutes : -1;
48}Key Explanations:
Let’s think about “Rotting Oranges” step by step:
Intuition:
Imagine a room full of oranges. Some are rotten, some are fresh. Every minute, rot spreads to adjacent fresh oranges. We want to know the minimum time until all oranges are rotten—or if it’s impossible.
Graph Model:
BFS Approach:
Why BFS?
Edge Cases:
Connecting Back:
By following this approach, you can confidently tackle similar problems involving spreading, shortest paths, or counting clusters in grids.
Signals to Recognize This Pattern:
Aha! Moments:
Debugging Tips:
Memory Tricks:
With practice, you’ll spot these patterns quickly and apply BFS with confidence!