1
var minCost = function (houses, cost, m, n, target) {4
function dfs(idx = 0, prevColor = -1, neighborhoods = 0) {5
if (idx === m) return neighborhoods === target ? 0 : Infinity;7
let key = `${idx}-${prevColor}-${neighborhoods}`;8
if (map.has(key)) return map.get(key);10
let color = houses[idx];11
// If the current house is already painted13
return color !== prevColor14
? dfs(idx + 1, color, neighborhoods + 1)15
: dfs(idx + 1, color, neighborhoods);18
let minCost = Infinity;19
for (let i = 1; i <= n; i++) {21
// If color i is !== prevColor, increment the neighborhood count22
if (i !== prevColor) potentialCost = dfs(idx + 1, i, neighborhoods + 1);23
// Otherwise, the neighborhood simply expanded so the neighborhood count stays the same24
else potentialCost = dfs(idx + 1, i, neighborhoods);26
if (potentialCost === Infinity) continue;27
minCost = Math.min(minCost, cost[idx][i - 1] + potentialCost);29
map.set(key, minCost);34
return minCost === Infinity ? -1 : minCost;