MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / min_path_sum

Function min_path_sum

graphs/minimum_path_sum.py:1–44  ·  view source on GitHub ↗

Find the path from top left to bottom right of array of numbers with the lowest possible sum and return the sum along this path. >>> min_path_sum([ ... [1, 3, 1], ... [1, 5, 1], ... [4, 2, 1], ... ]) 7 >>> min_path_sum([ ... [1, 0, 5, 6, 7],

(grid: list)

Source from the content-addressed store, hash-verified

1def 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
47def fill_row(current_row: list, row_above: list) -> list:

Callers

nothing calls this directly

Calls 1

fill_rowFunction · 0.85

Tested by

no test coverage detected