call(back)
Algorithms & Data StructureseasySign in to star problems

People and Cakes IV

Now the room is a grid, and every cell holds either a person (1) or a cake (2) — there are no empty cells. Return the smallest Manhattan distance between any person and any cake, or -1 if the grid lacks one of the two.

closestPair([[2, 1]])          ->  1
closestPair([[2], [1]])        ->  1
closestPair([[1, 1], [1, 1]])  ->  -1

Think before you search.

Hints

Hint 1

Start at any cake and walk toward any person one step at a time. Every step lands on a person or a cake — so what happens on the first step that changes kind?

Hint 2

If both kinds exist, that step is between neighbouring cells, so the minimum is always 1; the only work is checking that both exist.

Topics

Asked at

Similar Problems6