这个题解采用了BFS算法来解决问题。首先,我们获取森林中所有树的坐标和高度,并按高度从低到高排序。然后,从起点(0, 0)开始,依次砍掉每棵树。为了找到从当前位置到目标树的最短路径,我们使用BFS搜索。如果无法到达某棵树,则返回-1。否则,累加每次砍树所需的步数,直到砍完所有的树。最后返回总步数。
时间复杂度: O(k log k + k * mn)
空间复杂度: O(k + mn)
from collections import deque
from typing import List
class Solution:
def cutOffTree(self, forest: List[List[int]]) -> int:
if not forest or not forest[0]:
return -1
m, n = len(forest), len(forest[0])
trees = []
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] # right, left, down, up
# get all the trees' positions and heights
for i in range(m):
for j in range(n):
if forest[i][j] > 1:
trees.append((forest[i][j], i, j))
# if there is no tree, return -1
if not trees:
return -1
# sort the trees by their heights
trees.sort()
# bfs function
def bfs(sx, sy, tx, ty):
queue = deque([(sx, sy, 0)]) # (x, y, steps)
visited = [[False] * n for _ in range(m)]
visited[sx][sy] = True
while queue:
x, y, steps = queue.popleft()
if x == tx and y == ty:
return steps
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n and not visited[nx][ny] and forest[nx][ny] != 0:
visited[nx][ny] = True
queue.append((nx, ny, steps + 1))
return -1
# initial position
sx, sy = 0, 0
total_steps = 0
# cut the trees from the lowest to the highest
for _, tx, ty in trees:
steps = bfs(sx, sy, tx, ty)
# if we cannot reach the tree, return -1
if steps == -1:
return -1
total_steps += steps
sx, sy = tx, ty
return total_steps