subject : The original title is link ( secondary )
label : mathematics
solution
Time complexity
Spatial complexity
Execution time
Ans 1 (Python)
O ( N )
O ( N )
216ms (8.33%)
Ans 2 (Python)
Ans 3 (Python)
Solution 1 :
class Solution:
def minDistance(self, height: int, width: int, tree: List[int], squirrel: List[int], nuts: List[List[int]]) -> int:
d1 = [] # The distance from the pine cone to the tree
d2 = [] # Pinecones to squirrels + The distance from the pineal cone to the tree
for i1, i2 in nuts:
if 0 <= i1 < height and 0 <= i2 < width:
d1.append((abs(i1 - tree[0]) + abs(i2 - tree[1])) * 2)
d2.append(abs(i1 - tree[0]) + abs(i2 - tree[1]) + abs(i1 - squirrel[0]) + abs(i2 - squirrel[1]))
ans = 0
more = float("inf") # Distance change of the first pineal cone
for i in range(len(d1)):
ans += d1[i]
more = min(more, d2[i] - d1[i])
return ans + more