LeetCode 675
第一遍的时候我看题目不够仔细,对于这个“You are asked to cut off all the trees in this forest in the order of tree’s height - always cut off the tree with lowest height first. And after cutting, the original place has the tree will become a grass (value 1).” 关键信息没有get到。先去思考了如何以最短路径遍历所有的树,那样的话BFS还不够,需要回溯,不确定那个树是需要优先砍的才能走出最短路径。
第二遍看题目的时候才注意到这个信息,其实砍树的顺序是确定的,那么我们只要以BFS的方式去一棵棵砍就好了,如果能砍完,那么就有结果,如果不能那么就是-1.
def cutOffTree(self, forest: List[List[int]]) -> int:
if forest == None: raise Exception("invalid input")
m,n = len(forest), len(forest[0])
trees = []
for r in range(m):
for c in range(n):
if (forest[r][c] > 1):
trees.append(( forest[r][c], r,c))
trees.sort()
sr,sc = 0, 0
totalCost = 0
def bfs(forest, sr, sc, tr, tc, m, n):
queue =[(sr,sc,0)]
visted = [[False]*n for _ in range(m)]
visted[sr][sc] = True
while queue:
cr, cc, d = queue.pop(0)
if cr == tr and cc == tc: return d
for x, y in [[1,0],[-1,0], [0,1], [0,-1]]:
nr,nc = cr + x, cc + y
if 0<=nr<m and 0<=nc<n and (not visted[nr][nc]) and forest[nr][nc] > 0:
visted[nr][nc] = True
queue.append((nr,nc,d+1))
return -1
for tree in trees:
h, tr,tc = tree
d = bfs(forest, sr, sc, tr, tc, m, n)
if d == -1: return -1
totalCost +=d
sr, sc = tr, tc
return totalCost