Python BFS solution, not TLE.
Python solution, not TLE\n\n\nclass Solution(object):\n    def cutOffTree(self, forest):\n        """\n        :type forest: List[List[int]]\n        :rtype: in
Python solution, not TLE\n\n```\nclass Solution(object):\n    def cutOffTree(self, forest):\n        """\n        :type forest: List[List[int]]\n        :rtype: int\n        """\n        \n        def bfs(sx, sy, tx, ty, target, forest):\n            \n            q = collections.deque([(sx, sy)])\n            step = 0\n            saved = set()\n            saved.add((sx, sy))\n            \n            while q:\n                l = len(q)\n                for _ in range(l):\n                    cur = q.popleft()\n                    if cur == (tx, ty):\n                        return step\n                    dir = [(0,1), (0,-1),(1,0),(-1,0)]\n                    \n                    for dx, dy in dir:\n                        nx = cur[0] + dx\n                        ny = cur[1] + dy\n                        if nx < 0 or ny < 0 or nx >= len(forest) or ny >= len(forest[0]) or forest[nx][ny] == 0 or (nx, ny) in saved:\n                            continue\n                        saved.add((nx,ny))\n                        q.append((nx,ny))\n                step+=1\n            \n            return -1\n                    \n            \n        \n        m = len(forest[0])\n        n = len(forest)\n        tree = []\n        \n        for i in range(n):\n            for j in range(m):\n                if forest[i][j] > 1:\n                    tree.append((forest[i][j], i, j))\n        \n        tree.sort()\n        sx = 0\n        sy = 0\n        ans = 0\n        \n        for t in tree:\n            tx = t[1]\n            ty = t[2]\n            target = t[0]\n            \n            re = bfs(sx, sy, tx, ty, target, forest)\n            if re == -1:\n                return -1\n            ans += re\n            \n            sx, sy = tx, ty\n        return ans\n```
['Breadth-First Search', 'Python3']