Connected components + BFS

Measure Connected Garden Plots

Original & variantNumber of Islands ↗

This variant returns every component size, sorted descending, instead of just the count.

01. The question

A rectangular garden map uses 1 for planted ground and 0 for walkways. Planted cells belong to the same plot only when connected up, down, left, or right. Return every plot size sorted largest first. Keep equal sizes as separate entries.

Garden floor plan3 rows × 4 columns
r / c0123
01101
10100
21011

1 is planted ground; 0 is walkway. Only side-sharing cells belong to the same plot.

Before revealing the idea, predict the result and describe what information you would need to track.

02. Worked example

Inputgarden = [[1,1,0,1],[0,1,0,0],[1,0,1,1]]

Output[3, 2, 1, 1]

  1. Start at the first unvisited planted cell. BFS reaches three cells in the upper-left plot.
  2. The upper-right and lower-left cells each form a separate one-cell plot.
  3. The two lower-right cells form one plot. Sort the sizes, retaining both ones.

Try your code

Define solve(data, parameter="") and return your result. Your code runs locally, not on a server.

Edit your test cases

Use 1-10 objects with data and an optional string parameter. Expected outputs are computed from the lesson. An optional expected field must be correct.

Input contract & reference code

Example data: [[1,1,0,1],[0,1,0,0],[1,0,1,1]]. Parameter: "". Numeric parameters arrive as strings; convert them with int(parameter) when needed.

The example and generated cases use the question’s exact variant. This checks behavior on a small test batch—not performance on every possible input.

Python runtime notices

Python downloads only when you run code, using compressed runtime assets. Code is not saved or uploaded. Enable JavaScript to run it.

Five-second execution limit per batch. Standard-library Python only; additional packages and network access are unavailable. Stop ends execution without blocking the lesson.

03. The idea

Try sketching your own approach first. What would you track, and why would it work?

Reveal the idea
  1. Scan the grid for an unvisited planted cell.
  2. Start a new BFS and mark cells when enqueuing, so each is counted once.
  3. After each BFS, save its size. Sort the complete list descending.

04. Watch it happen

Use Step to move slowly, or Play to follow the whole trace. Change a preset or load your own input.

Input & settings

A nonempty rectangular 1-5 row by 1-5 column map. 1 = planted, 0 = walkway. Diagonals do not connect.

Red = current item / blue = active window or cells / green = completed work. A value docks at its actual destination; the original input stays unchanged. Positions start at 0.

Working state / what changes

Ready to begin

Enable JavaScript to step through the animation. The worked example and solution below remain readable without it.

Python / why it changes

The line behind the step

from collections import deque

def garden_plots(garden):
    rows, cols = len(garden), len(garden[0])
    seen = set()
    sizes = []
    for row in range(rows):
        for col in range(cols):
            if garden[row][col] == 0 or (row, col) in seen:
                continue
            queue = deque([(row, col)])
            seen.add((row, col))
            size = 0
            while queue:
                r, c = queue.popleft()
                size += 1
                for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                    nr, nc = r + dr, c + dc
                    if (0 <= nr < rows and 0 <= nc < cols
                            and garden[nr][nc] == 1 and (nr, nc) not in seen):
                        seen.add((nr, nc))
                        queue.append((nr, nc))
            sizes.append(size)
    return sorted(sizes, reverse=True)
How to use this walkthrough

Hover or focus a control for its label. Play forms the input and follows values into the working state. Step shows one change; Back and the slider restore exact snapshots. Reduced motion uses instant updates. Saved snapshots and sorted heap displays are teaching overhead, not algorithm complexity.

05. Python solution

from collections import deque

def garden_plots(garden):
    rows, cols = len(garden), len(garden[0])
    seen = set()
    sizes = []
    for row in range(rows):
        for col in range(cols):
            if garden[row][col] == 0 or (row, col) in seen:
                continue
            queue = deque([(row, col)])
            seen.add((row, col))
            size = 0
            while queue:
                r, c = queue.popleft()
                size += 1
                for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                    nr, nc = r + dr, c + dc
                    if (0 <= nr < rows and 0 <= nc < cols
                            and garden[nr][nc] == 1 and (nr, nc) not in seen):
                        seen.add((nr, nc))
                        queue.append((nr, nc))
            sizes.append(size)
    return sorted(sizes, reverse=True)

06. Cost & edge cases

Time
O(RC + p log(p + 1)), with p plots; sorting is part of the requested output
Space
O(RC)
  • Use a nonempty rectangular map; an all-walkway map returns [].
  • Diagonal touching does not connect plots.
  • Repeated sizes are not deduplicated. The input is not modified.

Keep going