@@ -3,24 +3,26 @@ int recursion(int i , int j, vector<vector<int> >&grid){
33 if (i<0 || j<0 || i == grid.size () || j == grid[0 ].size () || grid[i][j] == 0 ){
44 return 0 ;
55 }
6- int current = grid[i][j];
7- grid[i][j] = 0 ;
8- int ans = current;
9- int ans1 = 0 ;
10- ans1 = max (ans1,recursion (i-1 ,j,grid));
11- ans1 = max (ans1,recursion (i+1 ,j,grid));
12- ans1 = max (ans1, recursion (i,j+1 ,grid));
13- ans1 = max (ans1, recursion (i,j-1 ,grid));
14- ans+=ans1;
15- grid[i][j] = current;
16- return ans;
6+
7+ int originalGold = grid[r][c];
8+ grid[r][c] = 0 ; // Mark as visited by taking the gold
9+
10+ // Explore all 4 directions and find the path with the maximum gold
11+ int maxGoldFromNeighbors = 0 ;
12+ maxGoldFromNeighbors = max (maxGoldFromNeighbors, dfs (r + 1 , c, grid));
13+ maxGoldFromNeighbors = max (maxGoldFromNeighbors, dfs (r - 1 , c, grid));
14+ maxGoldFromNeighbors = max (maxGoldFromNeighbors, dfs (r, c + 1 , grid));
15+ maxGoldFromNeighbors = max (maxGoldFromNeighbors, dfs (r, c - 1 , grid));
16+
17+ grid[r][c] = originalGold; // Backtrack: put the gold back for other paths
18+ return originalGold + maxGoldFromNeighbors;
1719}
1820int getMaximumGold (vector<vector<int >>& grid) {
1921 int ans = 0 ;
2022 for (int i = 0 ; i<grid.size (); i++){
2123 for (int j = 0 ; j<grid[0 ].size ();j++){
2224 if (grid[i][j]!= 0 ){
23- ans = max (ans,recursion (i,j, grid));
25+ ans = max (ans, dfs (i, j, grid));
2426 }
2527 }
2628 }
0 commit comments