Path with Maximum Gold in C++

C++Server Side ProgrammingProgramming

Suppose 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 means that is empty. We have to find the maximum amount of gold that you can collect under the conditions −

  • Every time we are pointing a cell we will collect all the gold in that cell.
  • From our position we can walk one step to the left, right, up or down.
  • We cannot visit the same cell more than once.
  • Never visit a cell with 0 gold.

So if the input is like [[0,6,0],[5,8,7],[0,9,0]], then the result will be 24. The path to get maximum gold is 9 -> 8 -> 7

To solve this, we will follow these steps −

  • make one method called dfs, that is taking grid, n, m, i and j. That will act like below
  • if i >= n or j >= m or i<0 or j < 0 or grid[i, j] = -1 or grid[i, j] = 0, then return 0
  • temp := grid[i, j], cost := grid[i, j] and grid[i, j] = -1
  • cost := cost + maximum of dfs(grid, n, m, i + 1, j), dfs(grid, n, m, i – 1, j ) and dfs(grid, n, m, i, j – 1)
  • grid[i, j] := temp
  • return cost
  • the main method will be
  • n := rows of grid, m := columns of grid, ans := 0
  • for i in range 0 to n – 1
    • for j in range 0 to m – 1
      • if grid[i, j] is not 0, then ans := max of ans, dfs(grid, n, m, i, j)
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int dfs(vector<vector<int>>& grid, int n, int m, int i, int j){
      if(i>=n || j>=m ||i<0||j<0 || grid[i][j]==-1 || grid[i][j] == 0)return 0;
      int temp =grid[i][j];
      int cost = grid[i][j];
      grid[i][j] = -1;
      cost+=max({dfs(grid,n,m,i+1,j),dfs(grid,n,m,i-1,j),dfs(grid,n,m,i,j+1),dfs(grid,n,m,i,j-1)});
      grid[i][j] = temp;
      return cost;
   }
   int getMaximumGold(vector<vector<int>>& grid) {
      int n = grid.size() ;
      int m = grid[0].size();
      int ans = 0;
      for(int i =0;i<n;i++){
         for(int j =0;j<m;j++){
            if(grid[i][j]){
               //cout << "Start : " << i <<" " << j << endl;
               ans = max(ans,dfs(grid,n,m,i,j));
            }
         }
      }
      return ans;
   }
};
main(){
   vector<vector<int>> v = {{0,6,0},{5,8,7},{0,9,0}};
   Solution ob;
   cout << (ob.getMaximumGold(v));
}

Input

[[0,6,0],[5,8,7],[0,9,0]]

Output

24
raja
Published on 30-Apr-2020 12:54:02
Advertisements