Problem
You are given a 0-indexed 2D integer array grid
of size m x n
that represents a map of the items in a shop. The integers in the grid represent the following:
0
represents a wall that you cannot pass through.1
represents an empty cell that you can freely move to and from.- All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells.
It takes 1
step to travel between adjacent grid cells.
You are also given integer arrays pricing
and start
where pricing = [low, high]
and start = [row, col]
indicates that you start at the position
(row, col)
and are interested only in items with a price in the range of
[low, high]
(inclusive). You are further given an integer k
.
You are interested in the positions of the k
highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different:
- Distance, defined as the length of the shortest path from the
start
(shorter distance has a higher rank). - Price (lower price has a higher rank, but it must be in the price range).
- The row number (smaller row number has a higher rank).
- The column number (smaller column number has a higher rank).
Return thek
highest-ranked items within the price rangesorted by their rank (highest to lowest). If there are fewer than k
reachable items within the price range, return all of them.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
m == grid.length
n == grid[i].length
1 <= m, n <= 10^5
1 <= m * n <= 10^5
0 <= grid[i][j] <= 10^5
pricing.length == 2
2 <= low <= high <= 10^5
start.length == 2
0 <= row <= m - 1
0 <= col <= n - 1
grid[row][col] > 0
1 <= k <= m * n
Solution
Method 1 – Breadth-First Search with Sorting
Intuition
We want to find the k highest-ranked items within a price range, where rank is determined by shortest distance from the start, then by lowest price, then by row, then by column. BFS is ideal for finding shortest paths in a grid, and we can collect all valid items and sort them by the required criteria.
Approach
- Use BFS from the start cell to explore all reachable cells, tracking distance.
- For each cell, if its value is within the price range, record its (distance, price, row, col).
- After BFS, sort the collected items by (distance, price, row, col).
- Return the first k items’ positions.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m*n*log(m*n))
, where m and n are grid dimensions. BFS visits each cell once, and sorting all found items takes O(N log N) where N is the number of items. - 🧺 Space complexity:
O(m*n)
, for visited array, queue, and storing all valid items.