1219. Path with Maximum Gold
- 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)