K Highest Ranked Items Within a Price Range LeetCode solution in Python

1
# Runtime: 3258 ms (Top 98.66%) | Memory: 66 MB (Top 18.12%)
2
class Solution:
3
def highestRankedKItems(self, G, pricing, start, k):
4
m, n = len(G), len(G[0])
5
row, col = start
6
node = (0, G[row][col], row, col)
7
visited = set()
8
visited.add((row, col))
9
d = deque([node])
10
ans = []
11

12
while d:
13
dist, cost, row, col = d.popleft()
14
if pricing[0] <= cost <= pricing[1]:
15
ans += [(dist, cost, row, col)]
16

17
for x, y in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1):
18
if (
19
0 <= x <= m - 1
20
and 0 <= y <= n - 1
21
and (x, y) not in visited
22
and G[x][y] != 0
23
):
24
d.append((dist + 1, G[x][y], x, y))
25
visited.add((x, y))
26

27
ans = sorted(ans)
28

29
return [[x, y] for _, _, x, y in ans[:k]]

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0