Dataford
Interview Guides
Upgrade
All questions/Coding/Count Islands in a Grid

Count Islands in a Grid

Medium
Coding
Asked at 1 company1GraphsMatrix
Also asked at
Twitch

Problem

Given a 2D grid of '1' and '0', count how many islands it contains. An island is formed by horizontally or vertically adjacent land cells, and water separates different islands.

Examples

Example 1
Inputgrid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]Output1WhyAll land belongs to one connected component.
Example 2
Inputgrid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]Output3WhyThere are three disconnected groups of land.

Constraints

  • `1 <= rows, cols <= 300`
  • `grid[i][j]` is `'0'` or `'1'`
  • Only 4-directional adjacency counts

Problem

Given a 2D grid of '1' and '0', count how many islands it contains. An island is formed by horizontally or vertically adjacent land cells, and water separates different islands.

Examples

Example 1
Inputgrid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]Output1WhyAll land belongs to one connected component.
Example 2
Inputgrid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]Output3WhyThere are three disconnected groups of land.

Constraints

  • `1 <= rows, cols <= 300`
  • `grid[i][j]` is `'0'` or `'1'`
  • Only 4-directional adjacency counts
Practice Python
Python 3.10
Open on desktop for the full Python editor with syntax highlighting and autocomplete.