1
var minCost = function (houses, cost, m, n, target) {
2
let map = new Map();
3

4
function dfs(idx = 0, prevColor = -1, neighborhoods = 0) {
5
if (idx === m) return neighborhoods === target ? 0 : Infinity;
6

7
let key = `${idx}-${prevColor}-${neighborhoods}`;
8
if (map.has(key)) return map.get(key);
9

10
let color = houses[idx];
11
// If the current house is already painted
12
if (color > 0) {
13
return color !== prevColor
14
? dfs(idx + 1, color, neighborhoods + 1)
15
: dfs(idx + 1, color, neighborhoods);
16
}
17

18
let minCost = Infinity;
19
for (let i = 1; i <= n; i++) {
20
let potentialCost;
21
// If color i is !== prevColor, increment the neighborhood count
22
if (i !== prevColor) potentialCost = dfs(idx + 1, i, neighborhoods + 1);
23
// Otherwise, the neighborhood simply expanded so the neighborhood count stays the same
24
else potentialCost = dfs(idx + 1, i, neighborhoods);
25

26
if (potentialCost === Infinity) continue;
27
minCost = Math.min(minCost, cost[idx][i - 1] + potentialCost);
28
}
29
map.set(key, minCost);
30
return minCost;
31
}
32

33
let minCost = dfs();
34
return minCost === Infinity ? -1 : minCost;
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0