The Indian Engineer

Problem 1219 Path With Maximum Gold

Posted on 4 mins

Matrix Dfs Backtracking Cpp

Problem Statement

Link - Problem 1219

Question

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:

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

Solution

class Solution {
    const vector<pair<int,int>>direc = {{1,0},{-1,0},{0,-1},{0,1}};

    int checkIfAllNonZeros(vector<vector<int>>& grid){
        int count = 0;
        for(int i=0; i<grid.size(); i++){
            for(int j=0; j<grid[0].size(); j++){
                if(grid[i][j] != 0)
                    count += grid[i][j];
                else
                    return 0;
            }
        }

        return count;
    }

    int dfs(vector<vector<int>>& grid, int x, int y, const int& row, const int& col)
    {
        if(x<0 || y<0 || x>=row || y>= col || grid[x][y] == 0)
            return 0;

        int val = grid[x][y];
        grid[x][y] = 0;
        int localMax = val;
        for(const pair<int,int>& it:direc)
        {
            localMax = max(localMax, val + dfs(grid,x + it.first,y + it.second,row,col));
        }

        grid[x][y] = val;

        return localMax;
    }

public:
    int getMaximumGold(vector<vector<int>>& grid) {

        std::ios::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);

        int row = grid.size(), col = grid[0].size();
        int maxVal = 0;

        int count = checkIfAllNonZeros(grid);
        if(count) {
            return count;
        }


        for(int i = 0; i<row; i++)
        {
            for(int j = 0; j<col; j++)
            {
                if(grid[i][j] != 0)
                    maxVal = max(maxVal, dfs(grid,i,j,row,col));
            }
        }

        return maxVal;

    }
};

Complexity Analysis

Explanation

1. Intuition

2. Implementation

3. Functions


This problem enables us to apply DFS and backtracking to a 2 dimensional matrix.