Problem: K Highest Ranked Items Within a Price Range

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:

1. Distance, defined as the length of the shortest path from the `start` (shorter distance has a higher rank).
2. Price (lower price has a higher rank, but it must be in the price range).
3. The row number (smaller row number has a higher rank).
4. The column number (smaller column number has a higher rank).

Return the `k` highest-ranked items within the price range sorted by their
rank (highest to lowest). If there are fewer than `k` reachable items within
the price range, return all of them.


Python solution:
import math
import itertools
import bisect
import collections
import string
import heapq
import functools
import sortedcontainers
from typing import List, Dict, Tuple, Iterator

class Solution:
  def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]:
    dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))
    m = len(grid)
    n = len(grid[0])
    low, high = pricing
    row, col = start
    ans = []

    if low <= grid[row][col] <= high:
      ans.append([row, col])
      if k == 1:
        return ans

    q = collections.deque([(row, col)])
    seen = {(row, col)}

    while q:
      neighbors = []
      for _ in range(len(q)):
        i, j = q.popleft()
        for t in range(4):
          x = i + dirs[t][0]
          y = j + dirs[t][1]
          if x < 0 or x == m or y < 0 or y == n:
            continue
          if not grid[x][y] or (x, y) in seen:
            continue
          if low <= grid[x][y] <= high:
            neighbors.append([x, y])
          q.append((x, y))
          seen.add((x, y))
      neighbors.sort(key=lambda x: (grid[x[0]][x[1]], x[0], x[1]))
      for neighbor in neighbors:
        if len(ans) < k:
          ans.append(neighbor)
        if len(ans) == k:
          return ans

    return ans


Java solution:
class Solution {
  public List<List<Integer>> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) {
    final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    final int m = grid.length;
    final int n = grid[0].length;
    final int low = pricing[0];
    final int high = pricing[1];
    final int row = start[0];
    final int col = start[1];
    List<List<Integer>> ans = new ArrayList<>();

    if (low <= grid[row][col] && grid[row][col] <= high) {
      ans.add(Arrays.asList(row, col));
      if (k == 1)
        return ans;
    }

    Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(row, col)));
    boolean[][] seen = new boolean[m][n];
    seen[row][col] = true; // Mark as visited.

    while (!q.isEmpty()) {
      List<List<Integer>> neighbors = new ArrayList<>();
      for (int sz = q.size(); sz > 0; --sz) {
        final int i = q.peek().getKey();
        final int j = q.poll().getValue();
        for (int[] dir : DIRS) {
          final int x = i + dir[0];
          final int y = j + dir[1];
          if (x < 0 || x == m || y < 0 || y == n)
            continue;
          if (grid[x][y] == 0 || seen[x][y])
            continue;
          if (low <= grid[x][y] && grid[x][y] <= high)
            neighbors.add(Arrays.asList(x, y));
          q.offer(new Pair<>(x, y));
          seen[x][y] = true;
        }
      }
      Collections.sort(neighbors, new Comparator<List<Integer>>() {
        @Override
        public int compare(List<Integer> a, List<Integer> b) {
          final int x1 = a.get(0);
          final int y1 = a.get(1);
          final int x2 = b.get(0);
          final int y2 = b.get(1);
          if (grid[x1][y1] != grid[x2][y2])
            return grid[x1][y1] - grid[x2][y2];
          return x1 == x2 ? y1 - y2 : x1 - x2;
        }
      });
      for (List<Integer> neighbor : neighbors) {
        if (ans.size() < k)
          ans.add(neighbor);
        if (ans.size() == k)
          return ans;
      }
    }

    return ans;
  }
}


C++ solution:
class Solution {
 public:
  vector<vector<int>> highestRankedKItems(vector<vector<int>>& grid,
                                          vector<int>& pricing,
                                          vector<int>& start, int k) {
    constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    const int m = grid.size();
    const int n = grid[0].size();
    const int low = pricing[0];
    const int high = pricing[1];
    const int row = start[0];
    const int col = start[1];
    vector<vector<int>> ans;

    if (low <= grid[row][col] && grid[row][col] <= high) {
      ans.push_back({row, col});
      if (k == 1)
        return ans;
    }

    queue<pair<int, int>> q{{{row, col}}};
    vector<vector<bool>> seen(m, vector<bool>(n));
    seen[row][col] = true;  // Mark as visited.

    while (!q.empty()) {
      vector<vector<int>> neighbors;
      for (int sz = q.size(); sz > 0; --sz) {
        const auto [i, j] = q.front();
        q.pop();
        for (const auto& [dx, dy] : kDirs) {
          const int x = i + dx;
          const int y = j + dy;
          if (x < 0 || x == m || y < 0 || y == n)
            continue;
          if (!grid[x][y] || seen[x][y])
            continue;
          if (low <= grid[x][y] && grid[x][y] <= high)
            neighbors.push_back({x, y});
          q.emplace(x, y);
          seen[x][y] = true;
        }
      }
      ranges::sort(neighbors, [&](const vector<int>& a, const vector<int>& b) {
        const int x1 = a[0];
        const int y1 = a[1];
        const int x2 = b[0];
        const int y2 = b[1];
        if (grid[x1][y1] != grid[x2][y2])
          return grid[x1][y1] < grid[x2][y2];
        return x1 == x2 ? y1 < y2 : x1 < x2;
      });
      for (const vector<int>& neighbor : neighbors) {
        if (ans.size() < k)
          ans.push_back(neighbor);
        if (ans.size() == k)
          return ans;
      }
    }

    return ans;
  }
};