0
0
DSA Typescriptprogramming~3 mins

Why Number of Islands BFS and DFS in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

Discover how simple searches can solve tricky island counting problems in seconds!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
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
    }
  }
}
After
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++;
    }
  }
}
What It Enables

This lets you quickly and correctly count all islands on any map, no matter how big or complex, without missing or double counting.

Real Life Example

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.

Key Takeaways

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.