Discover how a simple search method can solve a tricky counting problem in maps!
Why Number of Islands BFS and DFS in DSA C?
Imagine you have a big map made of water and land squares. You want to count how many separate islands are on the map. Doing this by looking at each square and trying to remember which land belongs to which island can be very confusing and tiring.
Trying to count islands by checking each square manually is slow and easy to mess up. You might count the same island twice or miss some parts because it's hard to track connected land pieces without a clear method.
Using BFS (Breadth-First Search) or DFS (Depth-First Search) helps you explore each island fully before moving to the next. These methods automatically find all connected land squares, so you count each island exactly once without confusion.
int countIslands(char **grid, int rows, int cols) {
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == '1') {
// manually check neighbors and mark visited
count++;
}
}
}
return count;
}void dfs(char **grid, int row, int col, int rows, int cols) {
if (row < 0 || col < 0 || row >= rows || col >= cols || grid[row][col] == '0') return;
grid[row][col] = '0';
dfs(grid, row+1, col, rows, cols);
dfs(grid, row-1, col, rows, cols);
dfs(grid, row, col+1, rows, cols);
dfs(grid, row, col-1, rows, cols);
}
int countIslands(char **grid, int rows, int cols) {
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j, rows, cols);
count++;
}
}
}
return count;
}This lets you quickly and correctly find how many islands are on any map, no matter how big or complicated.
Think about a drone flying over a flooded area. It needs to count how many dry land patches (islands) are left to plan rescue missions. BFS or DFS helps the drone's software do this fast and without mistakes.
Manual counting is slow and error-prone.
BFS and DFS explore connected land fully to count islands correctly.
This method works well for maps of any size and shape.
Practice
Solution
Step 1: Understand the problem definition
The problem asks to find how many separate groups of connected '1's exist in the grid. Each group is called an island.Step 2: Identify what is counted
We count each cluster of adjacent '1's (connected horizontally or vertically) as one island.Final Answer:
Count how many groups of connected '1's (islands) are in the grid -> Option BQuick Check:
Number of islands = count of connected '1' groups [OK]
- Counting individual '1's instead of groups
- Including diagonal connections as connected
- Counting '0's instead of '1's
Solution
Step 1: Check parameter types for grid and indices
The grid is a 2D array of characters, passed as char** grid. Row and col are integers. Rows and cols are needed to check boundaries.Step 2: Verify function signature matches common DFS pattern
void dfs(int row, int col, char** grid, int rows, int cols) correctly uses void return type (no return needed), takes row, col, grid pointer, and grid size parameters.Final Answer:
void dfs(int row, int col, char** grid, int rows, int cols) -> Option DQuick Check:
Correct DFS signature includes grid pointer and size [OK]
- Using incorrect grid parameter type
- Missing grid size parameters
- Wrong return type for DFS
char* grid[] = {"11000", "11000", "00100", "00011"};
int rows = 4, cols = 5;What is the number of islands found by a correct BFS or DFS solution?
Solution
Step 1: Visualize the grid and connected '1's
Grid rows:
Row 0: 1 1 0 0 0
Row 1: 1 1 0 0 0
Row 2: 0 0 1 0 0
Row 3: 0 0 0 1 1
Islands are groups of connected '1's horizontally or vertically.Step 2: Count islands by grouping connected '1's
Island 1: Top-left block (positions (0,0),(0,1),(1,0),(1,1))
Island 2: Middle single '1' at (2,2)
Island 3: Bottom-right block (positions (3,3),(3,4))
Total islands = 3.Final Answer:
3 -> Option AQuick Check:
Count connected '1' groups = 3 [OK]
- Counting diagonal '1's as connected
- Missing isolated single '1's
- Misreading grid rows or columns
void dfs(int r, int c, char** grid, int rows, int cols) {
if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == '0')
return;
grid[r][c] = '0';
dfs(r+1, c, grid, rows, cols);
dfs(r-1, c, grid, rows, cols);
dfs(r, c+1, grid, rows, cols);
dfs(r, c-1, grid, rows, cols);
}Solution
Step 1: Analyze how visited cells are handled
The code sets grid[r][c] = '0' to mark visited cells, preventing revisiting.Step 2: Check if this approach is valid and complete
Marking visited by changing '1' to '0' is a common and valid method. The code checks boundaries and stops recursion correctly.Final Answer:
It correctly marks visited cells by setting '1' to '0', no bug -> Option CQuick Check:
Mark visited by changing '1' to '0' is correct [OK]
- Thinking grid modification is always wrong
- Expecting separate visited array
- Confusing diagonal neighbors as required
Solution
Step 1: Consider grid size and recursion limits
A 1000x1000 grid is large. Recursive DFS may cause stack overflow due to deep recursion.Step 2: Evaluate BFS advantages for large grids
BFS uses an explicit queue and avoids deep recursion, making it safer and efficient for large grids.Step 3: Check other options for correctness
DFS without marking visited causes infinite loops. Counting '1's directly misses island grouping.Final Answer:
Use BFS with a queue to avoid deep recursion and handle large grid efficiently -> Option AQuick Check:
Large grid + avoid recursion overflow = BFS [OK]
- Using recursive DFS causing stack overflow
- Not marking visited cells causing infinite loops
- Counting '1's without grouping
Ready to prove it?
Pass the test and this pattern moves unknown
