LeetCode 675

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值