CodePark/ problems / Count the Islands
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Graphs and topological sort

Count the Islands

mediumabout 20 minutes in an interview

grid is a map. Each cell is 1 for land or 0 for water. Count the islands and return the count.

Land cells that sit next to each other (up, down, left or right) are part of the same island. Diagonal neighbours don't join. Treat anything past the edge of the map as water.

  • The grid can be empty ([]). Then the answer is 0.
  • The grid is at most 300 × 300.
  • You're allowed to change the grid.
Input: grid = [[1, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 1, 0, 0], [1, 0, 0, 0, 0]] Output: 4There are four islands. A group of three at the top-left, a group of three at the top-right, the single 1 in the middle, and the single 1 at the bottom-left.
Input: grid = [[1, 1], [1, 1]] Output: 1