#675
Cut Off Trees for Golf Event
HardArrayBreadth-First SearchHeap (Priority Queue)Matrix
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + n²)Space O(n)
The optimal solution leverages a priority queue to always process the nearest tree first, ensuring that we minimize the number of steps taken. This approach efficiently finds the shortest paths to each tree in the required order.
⚙️
Algorithm
3 steps- 1Step 1: Extract and sort the trees by height, storing their coordinates.
- 2Step 2: Use a priority queue to perform a BFS from the current position to the next tree's position, ensuring we always take the shortest path.
- 3Step 3: Sum the steps for all trees. If any tree is unreachable, return -1.
solution.py35 lines
1from collections import deque
2import heapq
3
4def cutOffTree(forest):
5 def bfs(start, end):
6 if start == end:
7 return 0
8 queue = deque([start])
9 visited = set([start])
10 steps = 0
11 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
12 while queue:
13 for _ in range(len(queue)):
14 x, y = queue.popleft()
15 for dx, dy in directions:
16 nx, ny = x + dx, y + dy
17 if (0 <= nx < len(forest) and 0 <= ny < len(forest[0]) and
18 (nx, ny) not in visited and forest[nx][ny] > 0):
19 if (nx, ny) == end:
20 return steps + 1
21 visited.add((nx, ny))
22 queue.append((nx, ny))
23 steps += 1
24 return -1
25
26 trees = sorted([(forest[i][j], (i, j)) for i in range(len(forest)) for j in range(len(forest[0])) if forest[i][j] > 1])
27 total_steps = 0
28 start = (0, 0)
29 for height, (x, y) in trees:
30 steps = bfs(start, (x, y))
31 if steps == -1:
32 return -1
33 total_steps += steps
34 start = (x, y)
35 return total_stepsℹ
Complexity note: The time complexity is O(n log n) for sorting the trees and O(n²) for BFS in the worst case, leading to an overall complexity of O(n log n + n²).
- 1Using BFS ensures that we explore all possible paths efficiently.
- 2Sorting the trees by height allows us to prioritize cutting the shortest trees first.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.