In a gold mine grid
of size m x 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:
0
gold.For example:
grid = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24
Explanation: Path to get the maximum gold, 9 -> 8 -> 7.
grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
Output: 28
Explanation: Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 15
0 <= grid[i][j] <= 100
def getMaximumGold(grid):
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
max_gold = 0
def dfs(row, col, current_gold, visited):
nonlocal max_gold
max_gold = max(max_gold, current_gold)
# Possible directions: up, down, left, right
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
if 0 <= new_row < m and 0 <= new_col < n and \
grid[new_row][new_col] != 0 and (new_row, new_col) not in visited:
dfs(new_row, new_col, current_gold + grid[new_row][new_col], visited | {(new_row, new_col)})
for row in range(m):
for col in range(n):
if grid[row][col] != 0:
dfs(row, col, grid[row][col], {(row, col)})
return max_gold
Explanation:
Problem Understanding:
Naive Approach (Brute Force):
Optimal Solution:
def getMaximumGold(grid):
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
max_gold = 0
def dfs(row, col, current_gold, visited):
nonlocal max_gold
max_gold = max(max_gold, current_gold)
# Possible directions: up, down, left, right
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
if 0 <= new_row < m and 0 <= new_col < n and \
grid[new_row][new_col] != 0 and (new_row, new_col) not in visited:
dfs(new_row, new_col, current_gold + grid[new_row][new_col], visited | {(new_row, new_col)})
for row in range(m):
for col in range(n):
if grid[row][col] != 0:
dfs(row, col, grid[row][col], {(row, col)})
return max_gold
Big(O) Time Complexity Analysis:
dfs
function explores all possible paths. In the worst case, the algorithm explores all possible paths in the grid. This can be seen as a tree where each node has up to 4 children, and the depth is at most the number of cells in the grid (m * n). Hence the exponential nature.Big(O) Space Complexity Analysis:
visited
set can also contain up to m*n elements.visited
set, which stores the coordinates of visited cells, and the recursion stack depth. In the worst case, we might visit all cells, hence O(m*n).Edge Cases and Handling:
Alternative Approaches:
Summary:
The optimal solution for this problem is a DFS-based approach that explores all possible paths from each cell containing gold, while keeping track of visited cells to avoid cycles. The time complexity is O(4^(mn)), and the space complexity is O(mn). The algorithm handles edge cases such as empty grids, grids with no gold, and single-cell grids.