Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    Count the islands on a map

    MediumAbout 25 minFull AccessLearn it: Graphs with BFS and DFS in C#: Adjacency Lists, Grid Shortest Paths, Islands and Bipartite Checks

    The task

    A drone maps a coastline as a grid of '1' (land) and '0' (water). Land cells that touch up, down, left or right belong to the same island; cells that touch only at a corner do not.

    Complete CountIslands(char[][] grid). Return the number of islands. All rows have the same length; a grid with no rows has no islands.

    Signature

    public static int CountIslands(char[][] grid)

    Examples

    • ["1101011"] → 3. The land runs 11, 1 and 11 are separated by water.
    • ["10", "01"] → 2. The two land cells touch only at a corner.

    Limits: Up to 250,000 cells (for example 500 × 500). Grids are shown as rows of text; the tests turn each row into a char[].

    The tests check: a grid with no rows, all water, all land, cells that touch only at a corner, a ring of land around water, a U-shaped island, small and 500 × 500 checkerboards, and a 60 × 60 island.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public static class Solution
      {
          // Counts the groups of '1' cells joined up, down, left or right.
          public static int CountIslands(char[][] grid)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.