Python 3   || 19 lines   bfs   ||   T/S: 88% / 44%
This code is similar to those in other posts, with one exception. We use unseen to prune out the zero cells initially, and then keep track of the cells not visi
This code is similar to those in other posts, with one exception. We use `unseen` to prune out the zero cells initially, and then keep track of the cells *not* visited.\n```\nclass Solution:\n\n    def cutOffTree(self, forest: List[List[int]]) -> int:\n\n        def bfs(beg, end):\n            queue, uns = deque([(beg,0)]), unseen.copy()\n            uns.discard(beg)\n\n            while queue:\n                (r,c), steps = queue.popleft()\n\n                if (r,c) == end: return steps\n\n                for R,C in ((r-1,c), (r,c-1), (r+1,c), (r,c+1)):\n\n                    if (R,C) not in uns: continue\n\n                    queue.append(((R,C),steps+1))\n                    uns.discard((R,C))\n\n            return -1\n        \n        m, n, ans = len(forest), len(forest[0]), 0\n        start, trees = (0,0), []\n\n        grid = tuple(product(range(m), range(n)))\n        unseen = set(filter(lambda x: forest[x[0]][x[1]] != 0, grid))\n\n        for r,c  in grid:\n            if forest[r][c] > 1: heappush(trees,(forest[r][c], (r,c)))\n\n        while trees:\n            if (res:= bfs(start,(pos:= heappop(trees)[1]))) < 0: return -1\n\n            ans += res\n            start = pos\n\n        return ans\n```\n[https://leetcode.com/problems/cut-off-trees-for-golf-event/submissions/1271625830/](https://leetcode.com/problems/cut-off-trees-for-golf-event/submissions/1271625830/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*log*N*), in which *N* ~ number of cells in the 2D array`forest` (which is `len(forest)*len(forest[0])`).
['Python3']