BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Computer vision33 of 35 in topic

828. Count connected regions in a binary grid

MediumComputer vision Pro

Segmentation masks, occupancy maps and game boards are often stored as grids of 0 and 1. A common first step is to count how many separate regions of 1 cells there are.

Write count_islands(grid). grid is a list of equal-length strings made of '1' (land) and '0' (water). Two land cells belong to the same island if they touch up, down, left or right (not diagonally). Return the number of islands. An empty grid has 0 islands.

Functiondef count_islands(grid)

Example 1

Input: count_islands(['110', '010', '001'])

Output: 2

Example 2

Input: count_islands(['000'])

Output: 0

Constraints

  • 0 <= rows, cols <= 1,000
  • Cells are only '0' or '1'
Hint 1

Keep a seen matrix the same size as the grid.

Hint 2

Only start a fill from land that is not seen yet.

Hint 3

Mark cells as seen when you push them.

Common mistakes
  • Counting diagonal neighbours as connected.
  • Recursing deeply and hitting the recursion limit on big grids.
  • Forgetting the empty-grid case.
Understand the idea

Connected-component labelling turns a grid into a graph and floods each component once. For ['110', '010', '001'] the fill starting at (0, 0) marks (0, 1) and (1, 1), so the first island has three cells; (2, 2) starts a second island. Total work is O(rows x cols) because every cell is marked once.

Topics
Computer vision
Similar questions
  • Max pooling forward and backwardMedium
  • Detect edges with Sobel filters and a magnitude thresholdMedium
  • Unfold image patches with im2colMedium
  • Resize an image with bilinear interpolationMedium
All Computer vision problems
Report
828 / 903
Python 3solution.pyPython idle
1
2
3
4
def count_islands(grid):
# return the number of 4-connected regions of '1'
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS