KatInterview

Counting Land Clusters on a Wrap-Around Map

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsgraphdfsgrid

Last updated

Count connected groups of land cells on a grid whose opposite edges wrap around, testing grid traversal with modular adjacency.

You are given a rectangular map stored as a list of rows. Each cell holds 1 for land or 0 for water.

The map is wrap-around: the first and last rows are neighbors, and the first and last columns are neighbors. Think of the map as drawn on the surface of a donut.

Two land cells belong to the same cluster if you can walk from one to the other by repeatedly stepping to a land cell directly above, below, left or right of the current one. Stepping off one edge brings you to the opposite edge in the same row or column. Diagonal steps are not allowed.

Return the number of distinct land clusters.

Rules and edge cases:

  • Only cells whose value is exactly 1 count as land.
  • If the grid has no rows or no columns, return 0.
  • A grid with no land returns 0. A grid that is entirely land returns 1.
  • On very thin grids (one or two rows or columns), a cell's neighbors may coincide with each other or with the cell itself. This does not change the cluster count.
  • Do not worry about modifying the input; you may copy it or leave it unchanged.

Constraints

  • 0 <= m, n where m is the number of rows and n is the number of columns.
  • All rows have the same length.
  • The grid can be large (for example, 1000 x 1000), so avoid deep recursion.
  • Each value is an integer; only 1 is land.

Examples

Example 1

Input: count_wrapped_clusters([[1, 0, 0, 1], [0, 0, 0, 0], [1, 0, 0, 1]])

Output: 1

Example 2

Input: count_wrapped_clusters([[1, 1, 0], [0, 0, 0], [0, 0, 1]])

Output: 2

Example 3

Input: count_wrapped_clusters([[1, 1], [1, 1]])

Output: 1

Hints

Hint 1

Treat each land cell as a graph node. Its neighbors are the four adjacent cells, but with indices taken modulo the number of rows or columns.

Hint 2

Scan all cells. When you meet an unvisited land cell, increment the answer and flood-fill its whole cluster so it is never counted again.

Hint 3

Use an explicit stack or queue rather than recursion, and mark cells visited when you push them. Python's modulo operator already maps -1 to the last index.