Advertisement
DeepRest

K Highest Ranked Items Within a Price Range

Jan 23rd, 2022
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. class Solution:
  2.     def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]:
  3.         m, n = len(grid), len(grid[0])
  4.         dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
  5.         queue = deque([start])
  6.         res = []
  7.         if pricing[0]<=grid[start[0]][start[1]]<=pricing[1]:
  8.             res.append(start)
  9.         vis = set([(start[0], start[1])])
  10.         while queue:
  11.             sz = len(queue)
  12.             tmp = []
  13.             for _ in range(sz):
  14.                 a, b = queue.pop()
  15.                 for x, y in dirs:
  16.                     if 0<=a+x<m and 0<=b+y<n and (a+x, b+y) not in vis and grid[a+x][b+y] > 0:
  17.                         queue.appendleft([a+x, b+y])
  18.                         vis.add((a+x, b+y))
  19.                         if pricing[0]<=grid[a+x][b+y]<=pricing[1]:
  20.                             tmp.append([a+x, b+y])
  21.             tmp.sort(key=lambda x: (grid[x[0]][x[1]], x[0], x[1]))
  22.             res += tmp
  23.             if len(res) >= k:
  24.                 break
  25.        
  26.         return res[:k]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement