Number of Islands - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

  • We are given an m Γ— n grid where:
    • '1' represents land
    • '0' represents water
    Two land cells belong to the same island if they are connected horizontally or vertically (4-directionally).
  • We scan every cell in the grid:
    • When we encounter water or already explored land ('0'), we skip it.
    • When we encounter unvisited land '1', this cell marks the beginning of a new island. We increment islandCount and launch a BFS to explore all connected land cells ('1'), marking them as visited in-place (set to '0') so they won’t be counted again.
  • For each new island, we run a BFS:
    • The BFS queue is initialized with this starting cell and, throughout the search, it will hold land cells already confirmed to be part of this island but not yet dequeued to explore their unvisited neighboring land cells.
    • As soon as we add a land cell to the queue, we mark it as visited in-place by setting its value to '0'. This:
      • prevents reprocessing the same cell, and
      • removes the need for a separate visited matrix.
    • While the queue is not empty, we:
      • dequeue a cell (r, c),
      • look at its 4-directional neighbors (nr, nc),
      • for each neighbor that is inside the grid and has value '1', we:
        • mark it visited in-place by setting it to '0',
        • enqueue it to explore its own unvisited land neighbors in subsequent BFS steps.
      This BFS step ensures that all land cells connected to the starting cell are discovered and marked as part of the same island.
  • Once the BFS from a starting cell finishes, all cells in that island have been visited (set to '0'), so they will not start or belong to any other island. The outer scan then continues to look for the next unvisited land cell to start another island.

Time Complexity

Let m be the number of rows and n be the number of columns in the grid. We scan every cell once, and each land cell ('1') is visited, marked, and processed exactly once during BFS. Each cell may check up to four neighbors, but these operations take constant time overall. Hence, the total work done across all BFS traversals is proportional to the total number of cells, giving a time complexity of O(m Γ— n).

Space Complexity

Let m be the number of rows and n be the number of columns in the grid. The space complexity of this algorithm is O(min(m, n)). The worst case occurs when the grid is entirely filled with land cells, where the BFS queue can grow proportional to min(m, n) cells at its maximum.

Visucodize editorial solution titled JS Solution for LeetCode's Number of Islands coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/number-of-islands.