Problem Description
Given an m x n grid representing a shop, each cell is either a wall (0), an empty cell (1), or an item (a value greater than 1 representing its price). Starting from a given cell, you are to identify items whose price falls within a specified range [low, high]. The goal is to return the positions of the k highest-ranked items reachable, where ranking is determined by:
- Shortest distance from the start.
- Lower price.
- Smaller row index.
- Smaller column index. If fewer than k eligible items exist, return all of them.
Key Insights
- Use a Breadth-First Search (BFS) starting from the given cell to explore the grid and calculate the shortest path distances.
- Only consider cells that are reachable (i.e., not walls) and have an item price within the given range.
- Collect eligible items along with their distance, price, row, and column.
- Sort the collected items based on the required ranking criteria.
- Return the first k items according to the ranking.
Space and Time Complexity
Time Complexity: O(mn) due to the BFS traversal of the grid and O(E log E) for sorting E eligible items. Space Complexity: O(mn) for the visited array and BFS queue, plus O(E) for storing eligible items.
Solution
We solve the problem by performing a BFS starting from the given starting cell. During the BFS, each reachable cell is examined. If the cell contains an item whose price is between low and high (inclusive), the item along with its computed distance and position is added to a list of candidates. After the BFS completes, the candidates are sorted by distance, price, row, and column. Finally, the positions of the first k sorted candidates are returned. The primary data structures used are a queue for BFS and a list for storing candidate items.
Code Solutions
Below are code samples in Python, JavaScript, C++, and Java with line-by-line comments.