Cut Off Trees for Golf Event LeetCode solution in Python
1from collections import deque234class Solution:5def cutOffTree(self, forest: List[List[int]]) -> int:6a = []7n = len(forest)8m = len(forest[0])9for i in range(n):10for j in range(m):11if forest[i][j] > 1:12a.append(forest[i][j])13a.sort()1415s = 016ux = 017uy = 018for h in a:19dist = [[None] * m for i in range(n)]20q = deque()21q.append((ux, uy))22dist[ux][uy] = 023while q:24ux, uy = q.popleft()25if forest[ux][uy] == h:26break27d = [(-1, 0), (0, 1), (1, 0), (0, -1)]28for dx, dy in d:29vx = ux + dx30vy = uy + dy31if vx < 0 or vx >= n or vy < 0 or vy >= m:32continue33if forest[vx][vy] == 0:34continue35if dist[vx][vy] is None:36q.append((vx, vy))37dist[vx][vy] = dist[ux][uy] + 138if forest[ux][uy] == h:39s += dist[ux][uy]40else:41return -142return s