Skip to contentKEEP THE CRAFTTHE SANCTUARY

Visit Each Grid Component

Measure every connected region of 1s in a grid, in scan order.

The problem

Implement grid_component_sizes(grid). grid is a rectangular grid of 0s and 1s with at least one row and one column. Two 1-cells belong to the same component when you can walk from one to the other through 1-cells, moving up, down, left or right (diagonal moves do not count). Scan the grid row by row, from left to right, and return the size of each component in the order you first reach one of its cells.

Starter code

def grid_component_sizes(grid):
    pass

Public examples

  1. grid = [[1, 1, 0], [0, 1, 0], [1, 0, 1]]gives[3, 1, 1]
  2. grid = [[1, 0], [0, 1]]gives[1, 1]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.