Skip to content

1219. Path with Maximum Gold 👍

  • Time: $O(3^{mn})$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  int getMaximumGold(vector<vector<int>>& grid) {
    int ans = 0;

    for (int i = 0; i < grid.size(); ++i)
      for (int j = 0; j < grid[0].size(); ++j)
        ans = max(ans, dfs(grid, i, j));

    return ans;
  }

 private:
  int dfs(vector<vector<int>>& grid, int i, int j) {
    if (i < 0 || j < 0 || i == grid.size() || j == grid[0].size())
      return 0;
    if (grid[i][j] == 0)
      return 0;

    const int gold = grid[i][j];
    grid[i][j] = 0;  // Mark as visited.
    const int maxPath = max({dfs(grid, i + 1, j), dfs(grid, i - 1, j),
                             dfs(grid, i, j + 1), dfs(grid, i, j - 1)});
    grid[i][j] = gold;
    return gold + maxPath;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
  public int getMaximumGold(int[][] grid) {
    int ans = 0;

    for (int i = 0; i < grid.length; ++i)
      for (int j = 0; j < grid[0].length; ++j)
        ans = Math.max(ans, dfs(grid, i, j));

    return ans;
  }

  private int dfs(int[][] grid, int i, int j) {
    if (i < 0 || j < 0 || i == grid.length || j == grid[0].length)
      return 0;
    if (grid[i][j] == 0)
      return 0;

    final int gold = grid[i][j];
    grid[i][j] = 0; // Mark as visited.
    final int maxPath = Math.max(Math.max(dfs(grid, i + 1, j), dfs(grid, i - 1, j)),
                                 Math.max(dfs(grid, i, j + 1), dfs(grid, i, j - 1)));
    grid[i][j] = gold;
    return gold + maxPath;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def getMaximumGold(self, grid: list[list[int]]) -> int:
    def dfs(i: int, j: int) -> int:
      if i < 0 or j < 0 or i == len(grid) or j == len(grid[0]):
        return 0
      if grid[i][j] == 0:
        return 0

      gold = grid[i][j]
      grid[i][j] = 0  # Mark as visited.
      maxPath = max(dfs(i + 1, j), dfs(i - 1, j),
                    dfs(i, j + 1), dfs(i, j - 1))
      grid[i][j] = gold
      return gold + maxPath

    return max(dfs(i, j)
               for i in range(len(grid))
               for j in range(len(grid[0])))