Discover how simple searches can solve tricky island counting problems in seconds!
Why Number of Islands BFS and DFS in DSA Typescript?
Imagine you have a big map made of squares, some are water and some are land. 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 by hand is very hard and confusing.
Manually checking each square and trying to track connected lands is slow and easy to mess up. You might count the same island twice or miss some parts because it's hard to remember all connections 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.
let count = 0; for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { if (grid[i][j] === '1') { count++; // Manually try to mark connected lands } } }
function bfs(grid, startRow, startCol) {
let queue = [[startRow, startCol]];
grid[startRow][startCol] = '0';
while (queue.length > 0) {
let [row, col] = queue.shift();
let directions = [[1,0], [-1,0], [0,1], [0,-1]];
for (let [dr, dc] of directions) {
let r = row + dr, c = col + dc;
if (r >= 0 && r < grid.length && c >= 0 && c < grid[0].length && grid[r][c] === '1') {
queue.push([r, c]);
grid[r][c] = '0';
}
}
}
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (grid[i][j] === '1') {
bfs(grid, i, j);
count++;
}
}
}This lets you quickly and correctly count all islands on any map, no matter how big or complex, without missing or double counting.
Think about a drone flying over a flooded area. It needs to count how many separate dry land patches (islands) are left to plan rescue. BFS or DFS helps the drone's software do this fast and accurately.
Manually counting connected lands is confusing and error-prone.
BFS and DFS explore all connected parts of an island automatically.
This method ensures each island is counted once, making the task easy and reliable.