KatInterview

Count Separate Land Masses in a Grid

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphstrees-graphsdfs-bfsgrid

Last updated

Evaluate grid graph connectivity by finding the number of distinct 4-directionally connected land components.

Given a two-dimensional grid of characters representing a map, where '1' indicates land and '0' indicates open water, calculate the total number of distinct islands.

An island is defined as a maximal set of adjacent land cells connected orthogonally (up, down, left, right). Diagonal adjacencies are not considered connected.

Input consists of a list of string lists grid. You may mutate grid in-place if needed.

Constraints

  • m == len(grid)
  • n == len(grid[i])
  • 1 <= m, n <= 300
  • grid[i][j] is either '0' or '1'.

Examples

Example 1

Input: count_islands([['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: count_islands([['1', '1', '0', '0', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '0'], ['0', '0', '0', '1', '1']])

Output: 3

Example 3

Input: count_islands([['0', '0', '0'], ['0', '1', '0'], ['0', '0', '0']])

Output: 1

Hints

Hint 1

Model the grid as an unweighted, undirected graph where each '1' cell is a node and edges connect orthogonally adjacent '1' cells.

Hint 2

Traverse the grid sequentially. When you encounter an unvisited '1', increment your counter and run a BFS or DFS to visit and mark all reachable '1' cells.

Hint 3

To avoid stack overflow in Python on large landmasses, use an iterative traversal (queue or explicit stack) rather than direct recursion.