call(back)
Algorithms & Data Structuresmedium

Count Objects in a Pixel Grid via an API

A pin image is an H × W grid of pixels. You do not get the raw pixels; you get an opaque grid object:

grid.height() -> int
grid.width()  -> int
grid.isBackground(r, c) -> bool
grid.isSameObject(r1, c1, r2, c2) -> bool
    // defined for two 4-adjacent, in-bounds pixels; true iff both are
    // non-background AND belong to the same object

Count the distinct objects. An object is a maximal set of non-background pixels connected through 4-adjacent pairs for which isSameObject is true. Diagonal contact does not connect — and two touching non-background pixels may still be different objects (isSameObject says false).

A A . B          A B          A .
A . . B                       . A
. . C .
=> 3             => 2         => 2

H and W up to 2000 — avoid recursion; a 2000 × 2000 object blows the stack. Each API call is O(1).

Follow-ups

  • Solve it again with union-find over pixel ids.
  • The grid isn't available at all: you drive a robot with move(direction), isBackground(), and isSameObject(direction), starting on an unknown pixel — count the pixels of the object you are standing on (track relative coordinates).

Asked at