LC 200. Number of Islands

Alen Alex · February 8, 2024

LeetCode Link: 200. Number of Islands
Language: C#

Problem Statement

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.

Examples

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

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is ‘0’ or ‘1’.

Solution

public class Solution 
{
    public int NumIslands(char[][] grid) 
    {
        int count = 0;

        for (int i=0; i<grid.Length; i++)
        {
            for (int j=0; j< grid[i].Length; j++)
            {
                if (grid[i][j] == '1')
                {
                    count++;
                }
                DFS(grid, i, j);
            }
        }

        return count;
    }

    private void DFS(char[][] grid, int i, int j)
    {
        if (i < 0 || j < 0 || i > grid.Length - 1 || j > grid[i].Length -1 || grid[i][j] == '0')
        {
            return;
        }

        if (grid[i][j] == '1')
        {
            grid[i][j] = '0';
            DFS(grid, i-1, j); // UP
            DFS(grid, i, j-1); // LEFT
            DFS(grid, i, j+1); // RIGHT
            DFS(grid, i+1, j); // DOWN
        }
    }
}

Complexity

Time Complexity: O(N)
Space Complexity: O(N)

Twitter, Facebook