Blind 75
42 / 75Free practice

Number of Islands

Medium · Graphs

Jump to code

Count connected groups of land in a rectangular grid of 0s and 1s. Land connects horizontally or vertically, never diagonally.

Examples

Example 1

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

grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]

Output: 3

Constraints

  • 1 <= grid.length, grid[i].length <= 100
  • grid[i][j] is '0' or '1'.
Need a hint?

Each unseen land cell begins one component.

Asked in real interviews

Candidates reported versions of Number of Islands from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 11 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    [
      "1",
      "1",
      "1",
      "1",
      "0"
    ],
    [
      "1",
      "1",
      "0",
      "1",
      "0"
    ],
    [
      "1",
      "1",
      "0",
      "0",
      "0"
    ],
    [
      "0",
      "0",
      "0",
      "0",
      "0"
    ]
  ]
]
Expected
1
Case 2
Input
[
  [
    [
      "1",
      "1",
      "0",
      "0",
      "0"
    ],
    [
      "1",
      "1",
      "0",
      "0",
      "0"
    ],
    [
      "0",
      "0",
      "1",
      "0",
      "0"
    ],
    [
      "0",
      "0",
      "0",
      "1",
      "1"
    ]
  ]
]
Expected
3
Case 3
Input
[
  [
    [
      "0",
      "0",
      "0"
    ],
    [
      "0",
      "0",
      "0"
    ]
  ]
]
Expected
0
Case 4
Input
[
  [
    [
      "1",
      "0",
      "1",
      "0",
      "1"
    ]
  ]
]
Expected
3
Case 5
Input
[
  [
    []
  ]
]
Expected
0

Drafts are saved per language in this browser when storage is available.