这题首先要理解题意,题目要求我们把所有的树砍完。那必须按照由低到高的顺序依次砍树。所以需要把树由低到高进行排序。排序的时候需要记住坐标,然后从0,0出发,依次砍伐当前最矮的树
def cutOffTree(self, forest):
r = len(forest)
c = len(forest[0])
tree = []
for i in range(r): #把树按照高度排序
for j in range(c):
if (forest[i][j] > 1):
tree.append((forest[i][j],i,j))
tree.sort()
def bfs(x,y,tx,ty): #bfs是从x,y找到tx,ty的一条最短的路径。要想砍完,必须按照高度从低到高砍树,不然砍不完
queue = deque([(0,x,y)])
visited = set()
visited.add((x,y))
while queue:
d,x,y = queue.popleft()
if x==tx and y == ty:
return d
for nx,ny in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
if 0<= nx< r and 0<= ny < c and forest[nx][ny]!=0 and (nx,ny) not in visited: #矩阵中的位置不能为0,访问过的也不用考虑
queue.append((d+1,nx,ny))
visited.add((nx,ny))
return -1 #无法到达目标节点,返回-1
sx,sy = 0,0
ans = 0
for h,i,j in tree: #从0,0开始,找去最小的那棵树的路径长度,之后递归的找最矮的高度,逐渐增加
d = bfs(sx,sy,i,j)
if d < 0: #如果小于0,就直接返回-1
return -1
ans += d #不等于就把所有的最短路径相加
sx,sy = i,j #找下一个路径
return ans