Python Solution [Simplest] NOT TLE (BFS + Graph)
\nimport collections\nfrom functools import reduce\nclass Solution:\n    def cutOffTree(self, forest: List[List[int]]) -> int:\n        graph = collections.defa
```\nimport collections\nfrom functools import reduce\nclass Solution:\n    def cutOffTree(self, forest: List[List[int]]) -> int:\n        graph = collections.defaultdict(list)\n        m = len(forest)\n        n = len(forest[0])\n        for i in range(m):\n            for j in range(n):\n                if forest[i][j] != 0:\n                    north = forest[i-1][j] if i-1 >= 0 and forest[i-1][j] != 0 else None\n                    east = forest[i][j+1] if j+1 < n and forest[i][j+1] != 0 else None\n                    south = forest[i+1][j] if i+1 < m and forest[i+1][j] != 0 else None\n                    west = forest[i][j-1] if j-1 >= 0 and forest[i][j-1] != 0 else None\n                    graph[forest[i][j]] = list(filter(lambda x: x != None,[north,east,south,west]))\n        trees = []\n        for i in forest: trees.extend(filter(lambda x: x != 0 and x!= 1, i))\n        trees.sort()\n        moves = 0\n        initial_point = forest[0][0]\n        for i in trees:\n            tmp_move = self.min_dist(initial_point,i,graph)\n            if tmp_move == None:\n                return -1\n            moves += tmp_move\n            initial_point = i\n        return moves\n    \n    def min_dist(self,begin:int,target:int,graph:dict[int,list]) -> int:\n        visited = set()\n        stack = collections.deque([])\n        visited.add(begin)\n        distance = {}\n        for d in graph.keys() : distance[d] = None\n        distance[begin] = 0\n        stack.append(begin)\n        while len(stack) > 0:\n            t = stack.popleft()\n            if t == target:\n                return distance[t]\n            for i in graph[t]:\n                if i not in visited:\n                    visited.add(i)\n                    stack.append(i)\n                    distance[i] = distance[t] + 1\n            \n        \n```
[]