BFS +heights of trees in sorted order
\tclass Solution:\n\t\tdef bfs(self,v,i,j,n,m,forest):\n\t\t\tvis=set([i,j])\n\t\t\tq=deque([[i,j,0]])\n\t\t\twhile q:\n\t\t\t\tx,y,d=q.pop()\n\t\t\t\tif forest
\tclass Solution:\n\t\tdef bfs(self,v,i,j,n,m,forest):\n\t\t\tvis=set([i,j])\n\t\t\tq=deque([[i,j,0]])\n\t\t\twhile q:\n\t\t\t\tx,y,d=q.pop()\n\t\t\t\tif forest[x][y]==v:\n\t\t\t\t\treturn x,y,d\n\t\t\t\tfor i,j in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:\n\t\t\t\t\tif 0<=i<n and 0<=j<m and not (i,j) in vis and forest[i][j]:\n\t\t\t\t\t\tvis.add((i,j))\n\t\t\t\t\t\tq.appendleft([i,j,d+1])\n\t\t\treturn -1,-1,-1\n\n\t\tdef cutOffTree(self, forest: List[List[int]]) -> int:\n\t\t\torder=[]\n\t\t\tn,m=len(forest),len(forest[0])\n\t\t\tfor i in range(n):\n\t\t\t\tfor j in range(m):\n\t\t\t\t\tif forest[i][j]>1:\n\t\t\t\t\t\torder.append(forest[i][j])\n\t\t\torder.sort()\n\t\t\tres,x,y=0,0,0\n\t\t\tfor num in order:\n\t\t\t\tx,y,d=self.bfs(num,x,y,n,m,forest)\n\t\t\t\tif d==-1:\n\t\t\t\t\treturn -1\n\t\t\t\telse:\n\t\t\t\t\tres+=d\n\t\t\treturn res\n
['Breadth-First Search', 'Sorting']