Approach
Breadth-first search
For K Highest Ranked Items Within a Price Range, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 63 lines of C++ from the credited upstream file 2146.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<vector<int>> highestRankedKItems(vector<vector<int>>& grid,4 vector<int>& pricing,5 vector<int>& start, int k) {6 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};7 const int m = grid.size();8 const int n = grid[0].size();9 const int low = pricing[0];10 const int high = pricing[1];11 const int row = start[0];12 const int col = start[1];13 vector<vector<int>> ans;14 15 if (low <= grid[row][col] && grid[row][col] <= high) {16 ans.push_back({row, col});17 if (k == 1)18 return ans;19 }20 21 queue<pair<int, int>> q{{{row, col}}};22 vector<vector<bool>> seen(m, vector<bool>(n));23 seen[row][col] = true; 24 25 while (!q.empty()) {26 vector<vector<int>> neighbors;27 for (int sz = q.size(); sz > 0; --sz) {28 const auto [i, j] = q.front();29 q.pop();30 for (const auto& [dx, dy] : kDirs) {31 const int x = i + dx;32 const int y = j + dy;33 if (x < 0 || x == m || y < 0 || y == n)34 continue;35 if (!grid[x][y] || seen[x][y])36 continue;37 if (low <= grid[x][y] && grid[x][y] <= high)38 neighbors.push_back({x, y});39 q.emplace(x, y);40 seen[x][y] = true;41 }42 }43 ranges::sort(neighbors, [&](const vector<int>& a, const vector<int>& b) {44 const int x1 = a[0];45 const int y1 = a[1];46 const int x2 = b[0];47 const int y2 = b[1];48 if (grid[x1][y1] != grid[x2][y2])49 return grid[x1][y1] < grid[x2][y2];50 return x1 == x2 ? y1 < y2 : x1 < x2;51 });52 for (const vector<int>& neighbor : neighbors) {53 if (ans.size() < k)54 ans.push_back(neighbor);55 if (ans.size() == k)56 return ans;57 }58 }59 60 return ans;61 }62};63