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

Function solution

project_euler/problem_082/sol1.py:24–61  ·  view source on GitHub ↗

Returns the minimal path sum in the matrix from the file, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right >>> solution("test_matrix.txt") 994

(filename: str = "input.txt")

Source from the content-addressed store, hash-verified

22
23
24def solution(filename: str = "input.txt") -> int:
25 """
26 Returns the minimal path sum in the matrix from the file, by starting in any cell
27 in the left column and finishing in any cell in the right column,
28 and only moving up, down, and right
29
30 >>> solution("test_matrix.txt")
31 994
32 """
33
34 with open(os.path.join(os.path.dirname(__file__), filename)) as input_file:
35 matrix = [
36 [int(element) for element in line.split(",")]
37 for line in input_file.readlines()
38 ]
39
40 rows = len(matrix)
41 cols = len(matrix[0])
42
43 minimal_path_sums = [[-1 for _ in range(cols)] for _ in range(rows)]
44 for i in range(rows):
45 minimal_path_sums[i][0] = matrix[i][0]
46
47 for j in range(1, cols):
48 for i in range(rows):
49 minimal_path_sums[i][j] = minimal_path_sums[i][j - 1] + matrix[i][j]
50
51 for i in range(1, rows):
52 minimal_path_sums[i][j] = min(
53 minimal_path_sums[i][j], minimal_path_sums[i - 1][j] + matrix[i][j]
54 )
55
56 for i in range(rows - 2, -1, -1):
57 minimal_path_sums[i][j] = min(
58 minimal_path_sums[i][j], minimal_path_sums[i + 1][j] + matrix[i][j]
59 )
60
61 return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums)
62
63
64if __name__ == "__main__":

Callers 1

sol1.pyFile · 0.70

Calls 1

splitMethod · 0.80

Tested by

no test coverage detected