Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1219.html

1219. Path with Maximum Gold (Medium)

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.

 

Example 1:

Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24
Explanation:
[[0,6,0],
 [5,8,7],
 [0,9,0]]
Path to get the maximum gold, 9 -> 8 -> 7.

Example 2:

Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
Output: 28
Explanation:
[[1,0,7],
 [2,0,6],
 [3,4,5],
 [0,3,0],
 [9,0,20]]
Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.

 

Constraints:

  • 1 <= grid.length, grid[i].length <= 15
  • 0 <= grid[i][j] <= 100
  • There are at most 25 cells containing gold.

Related Topics: Backtracking

Solution 1. DFS

// OJ: https://leetcode.com/problems/path-with-maximum-gold/
// Time: O(MN*4^(MN))
// Space: O(MN) because in the worst case the DFS will visit all cells.
class Solution {
    int M, N, ans = 0, dirs[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
    void dfs(vector<vector<int>> &G, int i, int j, int cnt) {
        int g = G[i][j];
        G[i][j] = 0;
        cnt += g;
        ans = max(ans, cnt);
        for (auto &[dx, dy] : dirs) {
            int x = i + dx, y = j + dy;
            if (x < 0 || y < 0 || x >= M || y >= N || G[x][y] == 0) continue;
            dfs(G, x, y, cnt);
        }
        G[i][j] = g;
    }
public:
    int getMaximumGold(vector<vector<int>>& G) {
        M = G.size(), N = G[0].size();
        for (int i = 0; i < M; ++i) {
            for (int j = 0; j < N; ++j) {
                if (G[i][j] == 0) continue;
                dfs(G, i, j, 0);
            }
        }
        return ans;
    }
};
  • class Solution {
        int max = 0;
    
        public int getMaximumGold(int[][] grid) {
            int rows = grid.length, columns = grid[0].length;
            boolean[][] visited = new boolean[rows][columns];
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < columns; j++) {
                    if (grid[i][j] != 0)
                        backtrack(grid, i, j, 0, visited);
                }
            }
            return max;
        }
    
        public void backtrack(int[][] grid, int row, int column, int amount, boolean[][] visited) {
            int rows = grid.length, columns = grid[0].length;
            if (row < 0 || row >= rows || column < 0 || column >= columns || grid[row][column] == 0 || visited[row][column])
                max = Math.max(max, amount);
            else {
                amount += grid[row][column];
                visited[row][column] = true;
                int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
                for (int[] direction : directions)
                    backtrack(grid, row + direction[0], column + direction[1], amount, visited);
                amount -= grid[row][column];
                visited[row][column] = false;
            }
        }
    }
    
    ############
    
    class Solution {
        private int[][] grid;
        private int m;
        private int n;
    
        public int getMaximumGold(int[][] grid) {
            m = grid.length;
            n = grid[0].length;
            this.grid = grid;
            int ans = 0;
            for (int i = 0; i < m; ++i) {
                for (int j = 0; j < n; ++j) {
                    ans = Math.max(ans, dfs(i, j));
                }
            }
            return ans;
        }
    
        private int dfs(int i, int j) {
            if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) {
                return 0;
            }
            int t = grid[i][j];
            grid[i][j] = 0;
            int[] dirs = {-1, 0, 1, 0, -1};
            int ans = 0;
            for (int k = 0; k < 4; ++k) {
                ans = Math.max(ans, t + dfs(i + dirs[k], j + dirs[k + 1]));
            }
            grid[i][j] = t;
            return ans;
        }
    }
    
  • // OJ: https://leetcode.com/problems/path-with-maximum-gold/
    // Time: O(MN*4^(MN))
    // Space: O(MN) because in the worst case the DFS will visit all cells.
    class Solution {
        int M, N, ans = 0, dirs[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
        void dfs(vector<vector<int>> &G, int i, int j, int cnt) {
            int g = G[i][j];
            G[i][j] = 0;
            cnt += g;
            ans = max(ans, cnt);
            for (auto &[dx, dy] : dirs) {
                int x = i + dx, y = j + dy;
                if (x < 0 || y < 0 || x >= M || y >= N || G[x][y] == 0) continue;
                dfs(G, x, y, cnt);
            }
            G[i][j] = g;
        }
    public:
        int getMaximumGold(vector<vector<int>>& G) {
            M = G.size(), N = G[0].size();
            for (int i = 0; i < M; ++i) {
                for (int j = 0; j < N; ++j) {
                    if (G[i][j] == 0) continue;
                    dfs(G, i, j, 0);
                }
            }
            return ans;
        }
    };
    
  • class Solution:
        def getMaximumGold(self, grid: List[List[int]]) -> int:
            def dfs(i, j):
                if not (0 <= i < m and 0 <= j < n and grid[i][j]):
                    return 0
                t = grid[i][j]
                grid[i][j] = 0
                ans = t + max(
                    dfs(i + a, j + b) for a, b in [[0, 1], [0, -1], [-1, 0], [1, 0]]
                )
                grid[i][j] = t
                return ans
    
            m, n = len(grid), len(grid[0])
            return max(dfs(i, j) for i in range(m) for j in range(n))
    
    ############
    
    # 1219. Path with Maximum Gold
    # https://leetcode.com/problems/path-with-maximum-gold/
    
    class Solution:
        def getMaximumGold(self, grid: List[List[int]]):
            rows, cols = len(grid), len(grid[0])
            
            res = 0
            
            def dfs(x, y):
                tmp = grid[x][y]
                grid[x][y] = 0
                
                total = 0
                for dx,dy in ((x+1, y), (x-1, y), (x, y-1), (x, y+1)):
                    if 0 <= dx < rows and 0 <= dy < cols and grid[dx][dy] != 0:
                        total = max(total, grid[dx][dy] + dfs(dx,dy))
                
                grid[x][y] = tmp
                
                return total
                        
            
            for i in range(rows):
                for j in range(cols):
                    if grid[i][j] > 0:
                        res = max(res, grid[i][j] + dfs(i,j))
            
            return res
    
  • func getMaximumGold(grid [][]int) int {
    	m, n := len(grid), len(grid[0])
    	var dfs func(i, j int) int
    	dfs = func(i, j int) int {
    		if i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0 {
    			return 0
    		}
    		t := grid[i][j]
    		grid[i][j] = 0
    		ans := 0
    		dirs := []int{-1, 0, 1, 0, -1}
    		for k := 0; k < 4; k++ {
    			ans = max(ans, t+dfs(i+dirs[k], j+dirs[k+1]))
    		}
    		grid[i][j] = t
    		return ans
    	}
    	ans := 0
    	for i := 0; i < m; i++ {
    		for j := 0; j < n; j++ {
    			ans = max(ans, dfs(i, j))
    		}
    	}
    	return ans
    }
    
    func max(a, b int) int {
    	if a > b {
    		return a
    	}
    	return b
    }
    
  • /**
     * @param {number[][]} grid
     * @return {number}
     */
    var getMaximumGold = function (grid) {
        const m = grid.length;
        const n = grid[0].length;
        function dfs(i, j) {
            if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) {
                return 0;
            }
            const t = grid[i][j];
            grid[i][j] = 0;
            let ans = 0;
            const dirs = [-1, 0, 1, 0, -1];
            for (let k = 0; k < 4; ++k) {
                ans = Math.max(ans, t + dfs(i + dirs[k], j + dirs[k + 1]));
            }
            grid[i][j] = t;
            return ans;
        }
        let ans = 0;
        for (let i = 0; i < m; ++i) {
            for (let j = 0; j < n; ++j) {
                ans = Math.max(ans, dfs(i, j));
            }
        }
        return ans;
    };
    
    

All Problems

All Solutions