Skip to content

200. Number of Islands Medium

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 lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1

Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3

Approach

Input: A 2D grid made of '1' (land) and '0' (water)

Output: Compute the number of islands

This problem is a classic Grid Graph DFS scenario.

When traversing to a '1' (land), we must first mark this land piece as explored (by altering it to '0' or tracking it with a visited construct). Subsequently, we explore depth-first (DFS) checking neighboring coordinates recursively: up, down, left, and right, halting when hitting graph boundaries or water grids ('0').

This recursive exploring acts as the DFS pass.

Once components map tracking concludes dynamically, thoroughly linked elements convert representations into evaluated mapped safe zero variants.

Encountering independent fresh ones effectively signifies locating separated island boundaries counting sequentially upwards properly.

Implementation

python
from typing import List

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        rows, cols = len(grid), len(grid[0])  # Get row and column counts

        # Define DFS function used to "sink" the current evaluating island
        def dfs(r, c):
            # Checking bounds accurately verifying components structurally matching water elements mapping explicitly halting conditions properly naturally securely
            if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == '0':
                return
            
            # Submersing evaluating nodes explicitly marking processed avoiding mapped infinite loops successfully dynamically formatting correctly
            grid[r][c] = '0'

            # Traversal expanding tracking dynamically logically explicitly resolving neighbors naturally accurately seamlessly dependably smoothly cleanly
            dfs(r - 1, c)  # Up
            dfs(r + 1, c)  # Down
            dfs(r, c - 1)  # Left
            dfs(r, c + 1)  # Right

        count = 0  # Initialize islands counting sequence

        # Iterating navigating map evaluating successfully
        for r in range(rows):
            for c in range(cols):
                # Checking matching evaluated logic boundaries checking successfully
                if grid[r][c] == '1':
                    count += 1        # Register tracking components explicitly
                    dfs(r, c)         # Initiate sinking sequence explicitly naturally successfully mapping logically correctly explicitly cleanly
        
        return count  # Produce properly counted valid mapped total components uniquely isolated reliably returning evaluation output correctly cleanly properly logically securely gracefully dependably correctly
javascript
/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function(grid) {
    const rows = grid.length;
    const cols = grid[0].length;

    function dfs(r, c) {
        // Evaluating structurally verifying limits safely smoothly mapping naturally appropriately cleanly effectively returning
        if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] == '0')
            return
        
        grid[r][c] = '0';

        // Expansions recursive boundaries mapping
        dfs(r - 1, c);
        dfs(r + 1, c);
        dfs(r, c - 1);
        dfs(r, c + 1);
    }

    let count = 0;
    for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
            if (grid[r][c] == '1') {
                count++;
                dfs(r, c);
            }
        }
    }

    return count;
};

Complexity Analysis

  • Time Complexity: O(m * n) evaluating all components properly sequentially recursively
  • Space Complexity: O(m * n) matching deepest call stack recursion bounds gracefully structurally efficiently

200. Number of Islands (English)

200. 岛屿数量 (Chinese)