The Problem

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent land cells horizontally or vertically. You may assume all four edges of the grid are surrounded by water.

Interactive Visualization

Speed:
Grid Visualization
Code
fun numIslands(grid: Array<CharArray>): Int {    if (grid.isEmpty()) return 0    val rows = grid.size    val cols = grid[0].size    var count = 0    fun dfs(r: Int, c: Int) {        if (r < 0 || r >= rows ||            c < 0 || c >= cols ||            grid[r][c] != '1')            return        grid[r][c] = '#'  // mark visited        dfs(r + 1, c)        dfs(r - 1, c)        dfs(r, c + 1)        dfs(r, c - 1)    }    for (r in 0 until rows) {        for (c in 0 until cols) {            if (grid[r][c] == '1') {                count++                dfs(r, c)            }    }   }   return count }
Status
Press Step or Play to begin.

How It Works

Key Insight

Every unvisited land cell ('1') is either part of an already-counted island or the start of a brand-new one. When we find an unvisited '1', we increment the island count and use DFS to "flood fill" the entire connected component, marking every reachable land cell as visited so it won't be counted again.

The Algorithm

  • Scan: Iterate through every cell in the grid row by row, column by column.
  • Detect new island: When we encounter a '1' (unvisited land), increment count and launch a DFS from that cell.
  • DFS flood fill: Mark the current cell as visited ('#'), then recursively visit all four neighbors (up, down, left, right).
  • Base case: If the cell is out of bounds, water ('0'), or already visited ('#'), return immediately.
  • Result: After scanning the entire grid, count holds the total number of islands.

Complexity

Time O(m ร— n)
Space O(m ร— n)

Every cell is visited at most once during scanning and at most once during DFS, giving O(m ร— n) time. The space complexity is O(m ร— n) in the worst case for the recursion stack โ€” imagine a grid filled entirely with land, where DFS would recurse through all m ร— n cells.