Ctrl K

Nearest Affordable Goods

Medium
A shop floor plan is given as an m × n grid shop: - 0 is a wall you cannot pass; - 1 is an empty aisle; - any other number is an item with that price; you can walk over item cells too. You stand at start = [row, col], and each step moves you to a side-adjacent cell. You only care about reachable items whose price lies in price_range = [low, high], inclusive. Items are ranked by the first criterion that differs: 1. shortest path length from the start, shorter is better; 2. price, cheaper is better; 3. row index, smaller is better; 4. column index, smaller is better. Return the coordinates of the top count items in rank order, best first. If fewer items qualify, return all of them.
Example 1
shop=[[1, 4, 0], [3, 1, 2], [0, 6, 1]], price_range=[2, 4], start=[1, 1], count=2 → [[1, 2], [1, 0]]

All four neighbours of the start are one step away. The item priced 6 is out of range, leaving prices 2 at (1, 2), 3 at (1, 0) and 4 at (0, 1). At equal distance the cheaper item ranks higher, so the top two are [1, 2] and [1, 0].

Example 2
shop=[[2, 0, 5], [1, 0, 1], [1, 1, 1]], price_range=[2, 5], start=[0, 0], count=3 → [[0, 0], [0, 2]]

The item on the start cell counts too, at distance 0. The item at (0, 2) is reached by going around the wall from below, 6 steps. Only two items qualify, so both are returned.

Constraints
  • 1 ≤ m, n and m · n ≤ 10⁵
  • 0 ≤ shop[i][j] ≤ 10⁵
  • 2 ≤ low ≤ high ≤ 10⁵
  • start lies inside the grid and is not a wall
  • 1 ≤ count ≤ m · n
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsHow Far the Water Spreads HardK-th Smallest in a Sorted Grid MediumShortest Path of a Rolling Ball MediumRoute With the Highest Bottleneck MediumThe Gentlest Climb Medium
loading Python…
Input
shop=[[1, 4, 0], [3, 1, 2], [0, 6, 1]], price_range=[2, 4], start=[1, 1], count=2
Expected
[[1, 2], [1, 0]]

Run checks the first 3 tests in your browser. Submit checks all 43 tests on the server, hidden ones included.