Skip to content

Commit 7af7742

Browse files
authored
Create gold_mine_problem.py
1 parent 38b99b3 commit 7af7742

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# Python program to solve
2+
# Gold Mine problem
3+
4+
# Problem Statement : Returns maximum amount of
5+
# gold that can be collected
6+
# when journey started from
7+
# first column and moves
8+
# allowed are right, right-up
9+
# and right-down
10+
11+
# -----------------------------------------------------------------
12+
13+
# Approach : Brute Force Method
14+
# Abhishek S, 2021
15+
16+
# -----------------------------------------------------------------
17+
18+
MAX = 100
19+
20+
21+
def getMaxGold(gold, m, n):
22+
23+
# Create a table for storing
24+
# intermediate results
25+
# and initialize all cells to 0.
26+
# The first row of
27+
# goldMineTable gives the
28+
# maximum gold that the miner
29+
# can collect when starts that row
30+
goldTable = [[0 for i in range(n)]
31+
for j in range(m)]
32+
33+
for col in range(n-1, -1, -1):
34+
for row in range(m):
35+
36+
# Gold collected on going to
37+
# the cell on the rigth(->)
38+
if (col == n-1):
39+
right = 0
40+
else:
41+
right = goldTable[row][col+1]
42+
43+
# Gold collected on going to
44+
# the cell to right up (/)
45+
if (row == 0 or col == n-1):
46+
right_up = 0
47+
else:
48+
right_up = goldTable[row-1][col+1]
49+
50+
# Gold collected on going to
51+
# the cell to right down (\)
52+
if (row == m-1 or col == n-1):
53+
right_down = 0
54+
else:
55+
right_down = goldTable[row+1][col+1]
56+
57+
# Max gold collected from taking
58+
# either of the above 3 paths
59+
goldTable[row][col] = gold[row][col] + max(right, right_up, right_down)
60+
61+
# The max amount of gold
62+
# collected will be the max
63+
# value in first column of all rows
64+
res = goldTable[0][0]
65+
for i in range(1, m):
66+
res = max(res, goldTable[i][0])
67+
68+
return res
69+
70+
# Driver code
71+
gold = [[1, 3, 3],
72+
[2, 1, 4],
73+
[0, 6, 4]]
74+
75+
m = 3
76+
n = 3
77+
print ("- Gold Mine Problem using Dynamic Programming -")
78+
print ("-----------------------------------------------")
79+
print ()
80+
print ("Output : ")
81+
print ("The maximum amount of Gold can be collected : ")
82+
print(getMaxGold(gold, m, n))
83+
84+
85+
# -------------------------------------------------------------------------
86+
87+
# Output
88+
# - Gold Mine Problem using Dynamic Programming -
89+
# -----------------------------------------------
90+
91+
# Output :
92+
# The maximum amount of Gold can be collected :
93+
# 12
94+
95+
# -------------------------------------------------------------------------
96+
97+
# Code contributed by, Abhishek S, 2021

0 commit comments

Comments
 (0)