|
| 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