Skip to content

Commit 7c29082

Browse files
authored
Create min_cost_path.py
1 parent 75a7212 commit 7c29082

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
Author: MrDupin
3+
Created At: 25th August 2017
4+
"""
5+
import inspect
6+
7+
#Path(i, j) = min(Path(i-1, j), Path(i, j-1) + Matrix(i, j)
8+
9+
10+
def calculate_path(i, j, matrix, s):
11+
if(s[i][j] > 0):
12+
#We have already calculated solution for i,j; return it.
13+
return s[i][j]
14+
15+
m1 = calculate_path(i-1, j, matrix, s) + matrix[i][j] #Optimal solution for i-1, j (top)
16+
m2 = calculate_path(i, j-1, matrix, s) + matrix[i][j] #Optimal solution for i, j-1 (left)
17+
18+
#Store and return the optimal (minimum) solution
19+
if(m1 < m2):
20+
s[i][j] = m1
21+
return m1
22+
else:
23+
s[i][j] = m2
24+
return m2
25+
26+
27+
def find_path(matrix):
28+
l = len(matrix);
29+
#Initialize solution array.
30+
#A node of i, j in solution has an equivalent node of i, j in matrix
31+
s = [[0 for i in range(l)] for j in range(l)];
32+
33+
#Initialize first node as its matrix equivalent
34+
s[0][0] = matrix[0][0]
35+
36+
#Initialize first column as the matrix equivalent + the above solution
37+
for i in range(1, l):
38+
s[i][0] = matrix[i][0] + s[i-1][0]
39+
40+
#Initialize first row as the matrix equivalent + the left solution
41+
for j in range(1, l):
42+
s[0][j] = matrix[0][j] + s[0][j-1]
43+
44+
return calculate_path(l-1, l-1, matrix, s)
45+
46+
47+
def get_code():
48+
"""
49+
returns the code for the min cost path function
50+
"""
51+
return inspect.getsource(calculate_path)

0 commit comments

Comments
 (0)