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 Java from the credited upstream file 2146.java.
- 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 List<List<Integer>> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) {3 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};4 final int m = grid.length;5 final int n = grid[0].length;6 final int low = pricing[0];7 final int high = pricing[1];8 final int row = start[0];9 final int col = start[1];10 List<List<Integer>> ans = new ArrayList<>();11 12 if (low <= grid[row][col] && grid[row][col] <= high) {13 ans.add(Arrays.asList(row, col));14 if (k == 1)15 return ans;16 }17 18 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(row, col)));19 boolean[][] seen = new boolean[m][n];20 seen[row][col] = true; 21 22 while (!q.isEmpty()) {23 List<List<Integer>> neighbors = new ArrayList<>();24 for (int sz = q.size(); sz > 0; --sz) {25 final int i = q.peek().getKey();26 final int j = q.poll().getValue();27 for (int[] dir : DIRS) {28 final int x = i + dir[0];29 final int y = j + dir[1];30 if (x < 0 || x == m || y < 0 || y == n)31 continue;32 if (grid[x][y] == 0 || seen[x][y])33 continue;34 if (low <= grid[x][y] && grid[x][y] <= high)35 neighbors.add(Arrays.asList(x, y));36 q.offer(new Pair<>(x, y));37 seen[x][y] = true;38 }39 }40 Collections.sort(neighbors, new Comparator<List<Integer>>() {41 @Override42 public int compare(List<Integer> a, List<Integer> b) {43 final int x1 = a.get(0);44 final int y1 = a.get(1);45 final int x2 = b.get(0);46 final int y2 = b.get(1);47 if (grid[x1][y1] != grid[x2][y2])48 return grid[x1][y1] - grid[x2][y2];49 return x1 == x2 ? y1 - y2 : x1 - x2;50 }51 });52 for (List<Integer> neighbor : neighbors) {53 if (ans.size() < k)54 ans.add(neighbor);55 if (ans.size() == k)56 return ans;57 }58 }59 60 return ans;61 }62}63