2146. K Highest Ranked Items Within a Price Range (Medium) - TengnanYao/daily_leetcode GitHub Wiki

class Solution:
    def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]:
        m, n = len(grid), len(grid[0])
        q = [start]
        d = 0
        heap = []
        seen = set()
        while q and len(heap) < k:
            temp = set()
            d += 1
            for x, y in q:
                seen.add((x, y))
                if pricing[0] <= grid[x][y] <= pricing[1]:
                    heapq.heappush(heap, (d, grid[x][y], x, y))
                for dx, dy in (1, 0), (0, 1), (-1, 0), (0, -1):
                    i, j = x + dx, y + dy
                    if 0 <= i < m and 0 <= j < n and grid[i][j] != 0 and (i, j) not in seen:
                        temp.add((i, j))
            q = temp
        result = []
        while k and heap:
            _, _, x, y = heapq.heappop(heap)
            result.append([x, y])
            k -= 1
        return result