python: hadlock's algorithm, time complexity O((m*n)^2)
```\nclass Solution:\n    def cutOffTree(self, forest: List[List[int]]) -> int:\n        def dist(forest, sr, sc, tr, tc):\n            processed = set()\n     
```\nclass Solution:\n    def cutOffTree(self, forest: List[List[int]]) -> int:\n        def dist(forest, sr, sc, tr, tc):\n            processed = set()\n            deque = collections.deque([(0, sr, sc)])\n            while deque:\n                detours, r, c = deque.popleft()\n                if (r, c) not in processed:\n                    processed.add((r, c))\n                    if r == tr and c == tc:\n                        return abs(sr-tr) + abs(sc-tc) + 2*detours\n                    for nr, nc, closer in ((r-1, c, r > tr), (r+1, c, r < tr),\n                                   (r, c-1, c > tc), (r, c+1, c < tc)):\n                        if 0 <= nr < m and 0 <= nc < n and forest[nr][nc]:\n                            if closer:\n                                deque.appendleft((detours, nr, nc))\n                            else:\n                                deque.append((detours+1, nr, nc))\n            return -1\n        trees = []\n        m,n = len(forest),len(forest[0])\n        for i in range(m):\n            for j in range(n):\n                if forest[i][j] > 1:\n                    trees.append([forest[i][j],i,j])\n        trees = sorted(trees)\n                \n        sr = sc = ans = 0\n        for _, tr, tc in trees:\n            d = dist(forest, sr, sc, tr, tc)\n            if d < 0: return -1\n            ans += d\n            sr, sc = tr, tc\n        return ans
[]