Skip to content

Commit b8fdd81

Browse files
rainelegarypoyea
andauthored
Add minmum path sum (TheAlgorithms#5882)
* commit on 'shortest_path_sum' * minimum_path_sum updated * commit to 'minimum_path_sum' * added description to minimum_path_sum * bot requirements fixed for * Update minimum_path_sum.py * Update minimum_path_sum.py Co-authored-by: John Law <[email protected]>
1 parent de4d980 commit b8fdd81

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

graphs/minimum_path_sum.py

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
def min_path_sum(grid: list) -> int:
2+
"""
3+
Find the path from top left to bottom right of array of numbers
4+
with the lowest possible sum and return the sum along this path.
5+
>>> min_path_sum([
6+
... [1, 3, 1],
7+
... [1, 5, 1],
8+
... [4, 2, 1],
9+
... ])
10+
7
11+
12+
>>> min_path_sum([
13+
... [1, 0, 5, 6, 7],
14+
... [8, 9, 0, 4, 2],
15+
... [4, 4, 4, 5, 1],
16+
... [9, 6, 3, 1, 0],
17+
... [8, 4, 3, 2, 7],
18+
... ])
19+
20
20+
21+
>>> min_path_sum(None)
22+
Traceback (most recent call last):
23+
...
24+
TypeError: The grid does not contain the appropriate information
25+
26+
>>> min_path_sum([[]])
27+
Traceback (most recent call last):
28+
...
29+
TypeError: The grid does not contain the appropriate information
30+
"""
31+
32+
if not grid or not grid[0]:
33+
raise TypeError("The grid does not contain the appropriate information")
34+
35+
for cell_n in range(1, len(grid[0])):
36+
grid[0][cell_n] += grid[0][cell_n - 1]
37+
row_above = grid[0]
38+
39+
for row_n in range(1, len(grid)):
40+
current_row = grid[row_n]
41+
grid[row_n] = fill_row(current_row, row_above)
42+
row_above = grid[row_n]
43+
44+
return grid[-1][-1]
45+
46+
47+
def fill_row(current_row: list, row_above: list) -> list:
48+
"""
49+
>>> fill_row([2, 2, 2], [1, 2, 3])
50+
[3, 4, 5]
51+
"""
52+
53+
current_row[0] += row_above[0]
54+
for cell_n in range(1, len(current_row)):
55+
current_row[cell_n] += min(current_row[cell_n - 1], row_above[cell_n])
56+
57+
return current_row
58+
59+
60+
if __name__ == "__main__":
61+
import doctest
62+
63+
doctest.testmod()

0 commit comments

Comments
 (0)