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

1
var highestRankedKItems = function (grid, pricing, start, k) {
2
const m = grid.length;
3
const n = grid[0].length;
4
const dirs = [-1, 0, 1, 0, -1];
5

6
const visited = [];
7

8
for (let i = 0; i < m; ++i) {
9
visited[i] = new Array(n).fill(false);
10
}
11

12
const [low, high] = pricing;
13

14
const queue = [];
15

16
queue.push([...start, 0]);
17

18
const items = [];
19

20
while (queue.length > 0) {
21
const [row, col, dist] = queue.shift();
22

23
if (visited[row][col]) continue;
24

25
visited[row][col] = true;
26

27
const price = grid[row][col];
28

29
if (withinRange(price, low, high)) {
30
items.push({ dist, price, row, col });
31
}
32

33
for (let i = 0; i < dirs.length - 1; ++i) {
34
const neiRow = row + dirs[i];
35
const neiCol = col + dirs[i + 1];
36

37
if (
38
withinBound(neiRow, neiCol) &&
39
!visited[neiRow][neiCol] &&
40
grid[neiRow][neiCol] != 0
41
) {
42
queue.push([neiRow, neiCol, dist + 1]);
43
}
44
}
45
}
46

47
items.sort(compareFunc);
48

49
const res = [];
50

51
for (let i = 0; i < Math.min(k, items.length); ++i) {
52
const { dist, price, row, col } = items[i];
53

54
res.push([row, col]);
55
}
56

57
return res;
58

59
function withinRange(price, low, high) {
60
return low <= price && price <= high;
61
}
62

63
function withinBound(row, col) {
64
return row >= 0 && col >= 0 && row < m && col < n;
65
}
66

67
function compareFunc(a, b) {
68
return (
69
a.dist - b.dist || a.price - b.price || a.row - b.row || a.col - b.col
70
);
71
}
72
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0