1+ package dp ;
2+
3+ import java .util .Arrays ;
4+ // Problem Title => Gold Mine Problem
5+ public class DP_Problem_10 {
6+
7+ static final int MAX = 100 ;
8+
9+ // Returns maximum amount of gold that can be collected when journey started from first column and moves allowed are right,
10+ // right-up and right-down
11+ static int getMaxGold (int [][] gold , int m , int n )
12+ {
13+
14+ // Create a table for storing intermediate results and initialize all cells to 0.
15+ // The first row of goldMineTable gives the maximum gold that the miner can collect when starts that row
16+ int [][] goldTable = new int [m ][n ];
17+
18+ for (int [] rows :goldTable )
19+ Arrays .fill (rows , 0 );
20+
21+ for (int col = n -1 ; col >= 0 ; col --)
22+ {
23+ for (int row = 0 ; row < m ; row ++)
24+ {
25+
26+ // Gold collected on going to the cell on the right(->)
27+ int right = (col == n -1 ) ? 0
28+ : goldTable [row ][col +1 ];
29+
30+ // Gold collected on going to the cell to right up (/)
31+ int right_up = (row == 0 ||
32+ col == n -1 ) ? 0 :
33+ goldTable [row -1 ][col +1 ];
34+
35+ // Gold collected on going to the cell to right down (\)
36+ int right_down = (row == m -1
37+ || col == n -1 ) ? 0 :
38+ goldTable [row +1 ][col +1 ];
39+
40+ // Max gold collected from taking either of the above 3 paths
41+ goldTable [row ][col ] = gold [row ][col ] + Math .max (right , Math .max (right_up , right_down ));
42+ }
43+ }
44+
45+ // The max amount of gold collected will be the max value in first column of all rows
46+ int res = goldTable [0 ][0 ];
47+
48+ for (int i = 1 ; i < m ; i ++)
49+ res = Math .max (res , goldTable [i ][0 ]);
50+
51+ return res ;
52+ }
53+
54+ //driver code
55+ public static void main (String [] arg )
56+ {
57+ int [][] gold = { {1 , 3 , 1 , 5 },
58+ {2 , 2 , 4 , 1 },
59+ {5 , 0 , 2 , 3 },
60+ {0 , 6 , 1 , 2 } };
61+
62+ int m = 4 , n = 4 ;
63+
64+ System .out .print (getMaxGold (gold , m , n ));
65+ }
66+ }
0 commit comments