Skip to content

Commit 52b3cf1

Browse files
author
Partho Biswas
committed
1219. Path with Maximum Gold
1 parent 8e2d66a commit 52b3cf1

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution(object):
2+
def getMaximumGold(self, grid):
3+
"""
4+
:type grid: List[List[int]]
5+
:rtype: int
6+
"""
7+
totalGoldCollections = []
8+
for rowIdx in range(len(grid)):
9+
for colIdx in range(len(grid[0])):
10+
if grid[rowIdx][colIdx] != 0:
11+
self.calculateGoldCollections(rowIdx, colIdx, 0, grid, totalGoldCollections)
12+
return max(totalGoldCollections)
13+
14+
def calculateGoldCollections(self, rowIdx, colIdx, currentCollection, grid, totalGoldCollections):
15+
if rowIdx < 0 or rowIdx >= len(grid) or colIdx < 0 or colIdx >= len(grid[0]) or grid[rowIdx][colIdx] == 0:
16+
totalGoldCollections.append(currentCollection)
17+
return # Backtrack
18+
currentCellGold = grid[rowIdx][colIdx]
19+
grid[rowIdx][colIdx] = 0 # To prevent revisiting the cell
20+
currentCollection += currentCellGold
21+
self.calculateGoldCollections(rowIdx - 1, colIdx, currentCollection, grid,
22+
totalGoldCollections) # walk one step to the up
23+
self.calculateGoldCollections(rowIdx, colIdx - 1, currentCollection, grid,
24+
totalGoldCollections) # walk one step to the left
25+
self.calculateGoldCollections(rowIdx + 1, colIdx, currentCollection, grid,
26+
totalGoldCollections) # walk one step to the down
27+
self.calculateGoldCollections(rowIdx, colIdx + 1, currentCollection, grid,
28+
totalGoldCollections) # walk one step to the right
29+
grid[rowIdx][colIdx] = currentCellGold # Restoring the grid
30+
currentCollection -= currentCellGold # recalculating collections
31+
32+
33+
34+

0 commit comments

Comments
 (0)