readable python solution using Heap and BFS
\ndef cutOffTree(self, forest):\n        """\n        :type forest: List[List[int]]\n        :rtype: int\n        """\n        m, n = len(forest), len(forest[0]
```\ndef cutOffTree(self, forest):\n        """\n        :type forest: List[List[int]]\n        :rtype: int\n        """\n        m, n = len(forest), len(forest[0])\n        heap = [(forest[i][j], i, j) for i in range(m) for j in range(n) if forest[i][j] > 1]\n        heapq.heapify(heap)\n\n        def get_distance(x1, y1, x2, y2):\n            if x1 == x2 and y1 == y2:\n                return 0\n            queue, dist, visited = [(x1, y1)], 0, {(x1, y1)}\n            while queue:\n                new_queue = []\n                dist += 1\n                for r, c in queue:\n                    for dir in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n                        nr, nc = r + dir[0], c + dir[1]\n                        if 0 <= nr < m and 0 <= nc < n and (nr, nc) not in visited and forest[nr][nc] != 0:\n                            visited.add((nr, nc))\n                            if nr == x2 and nc == y2:\n                                return dist\n                            new_queue.append((nr, nc))\n                queue = new_queue\n            return -1\n\n        res = 0\n        x, y = 0, 0\n        while heap:\n            _, nx, ny = heapq.heappop(heap)\n            dist = get_distance(x, y, nx, ny)\n            if dist == -1:\n                return -1\n            res += dist\n            x, y = nx, ny\n\n        return res\n```
[]