TheAlgorithms-Python
48 строк · 1.5 Кб
1"""
2Problem 81: https://projecteuler.net/problem=81
3In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right,
4by only moving to the right and down, is indicated in bold red and is equal to 2427.
5
6[131] 673 234 103 18
7[201] [96] [342] 965 150
8630 803 [746] [422] 111
9537 699 497 [121] 956
10805 732 524 [37] [331]
11
12Find the minimal path sum from the top left to the bottom right by only moving right
13and down in matrix.txt (https://projecteuler.net/project/resources/p081_matrix.txt),
14a 31K text file containing an 80 by 80 matrix.
15"""
16
17import os18
19
20def solution(filename: str = "matrix.txt") -> int:21"""22Returns the minimal path sum from the top left to the bottom right of the matrix.
23>>> solution()
24427337
25"""
26with open(os.path.join(os.path.dirname(__file__), filename)) as in_file:27data = in_file.read()28
29grid = [[int(cell) for cell in row.split(",")] for row in data.strip().splitlines()]30dp = [[0 for cell in row] for row in grid]31n = len(grid[0])32
33dp = [[0 for i in range(n)] for j in range(n)]34dp[0][0] = grid[0][0]35for i in range(1, n):36dp[0][i] = grid[0][i] + dp[0][i - 1]37for i in range(1, n):38dp[i][0] = grid[i][0] + dp[i - 1][0]39
40for i in range(1, n):41for j in range(1, n):42dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])43
44return dp[-1][-1]45
46
47if __name__ == "__main__":48print(f"{solution() = }")49