Cut Off Trees for Golf Event LeetCode solution in JavaScript
1var cutOffTree = function (forest) {2const trees = forest3.flat()4.filter((x) => x && x !== 1)5.sort((a, b) => b - a);6let currPos = [0, 0],7totalDist = 0;89while (trees.length) {10const grid = [...forest.map((row) => [...row])];11const res = getDist(currPos, trees.pop(), grid);12if (res == null) return -1;13const [pos, dist] = res;14currPos = pos;15totalDist += dist;16}17return totalDist;1819function getDist(start, target, grid) {20const dir = [21[1, 0],22[-1, 0],23[0, 1],24[0, -1],25];26let queue = [start],27dist = 0;2829while (queue.length) {30const next = [];3132for (let [r, c] of queue) {33if (grid[r][c] === target) return [[r, c], dist];34if (!grid[r][c]) continue;3536for (let [x, y] of dir) {37x += r;38y += c;39if (40x >= 0 &&41x < grid.length &&42y >= 0 &&43y < grid[0].length &&44grid[x][y]45)46next.push([x, y]);47}48grid[r][c] = 0;49}50dist++;51queue = next;52}53return null;54}55};