LeetCode 1219. Path with Maximum Gold解题报告(python)

1219. Path with Maximum Gold

  1. Path with Maximum Gold python solution

题目描述

In a gold mine grid of size m * n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.
Return the maximum amount of gold you can collect under the conditions:
Every time you are located in a cell you will collect all the gold in that cell.
From your position you can walk one step to the left, right, up or down.
You can’t visit the same cell more than once.
Never visit a cell with 0 gold.
You can start and stop collecting gold from any position in the grid that has some gold.
在这里插入图片描述

解析

还是要采用递归的思想解题,每个节点只能向上,下,左,右四个方向前进。如果该点的黄金为0,那么就不能去往该点。在该点取金后,前往下一节点。记录此时的总金量,更新总金量的最大值。
要将节点的黄金值复原,以便下一次递归搜索。

class Solution:
    def getMaximumGold(self, grid: List[List[int]]) -> int:
        m=len(grid)
        n=len(grid[0])
        self.res=0
        def dfs(x,y,gold):
            self.res=max(self.res,gold)
            for (i,j) in ((x+1,y),(x-1,y),(x,y+1),(x,y-1)):
                if 0<=i<m and 0<=j<n and grid[i][j]!=0:
                    v=grid[i][j]
                    grid[i][j]=0
                    dfs(i,j,gold+v)
                    grid[i][j]=v
        
        for i in range (m):
            for j in range (n):
                if grid[i][j]!=0:
                    x=grid[i][j]
                    grid[i][j]=0
                    dfs(i,j,x)
                    grid[i][j]=x
        return self.res

Reference

https://leetcode.com/problems/path-with-maximum-gold/discuss/400717/Python3-Concise-DFS-Easy-to-understand-(no-using-set)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值