Returns the minimal path sum from the top left to the bottom right of the matrix. >>> solution() 427337
(filename: str = "matrix.txt")
| 18 | |
| 19 | |
| 20 | def solution(filename: str = "matrix.txt") -> int: |
| 21 | """ |
| 22 | Returns the minimal path sum from the top left to the bottom right of the matrix. |
| 23 | >>> solution() |
| 24 | 427337 |
| 25 | """ |
| 26 | with open(os.path.join(os.path.dirname(__file__), filename)) as in_file: |
| 27 | data = in_file.read() |
| 28 | |
| 29 | grid = [[int(cell) for cell in row.split(",")] for row in data.strip().splitlines()] |
| 30 | dp = [[0 for cell in row] for row in grid] |
| 31 | n = len(grid[0]) |
| 32 | |
| 33 | dp = [[0 for i in range(n)] for j in range(n)] |
| 34 | dp[0][0] = grid[0][0] |
| 35 | for i in range(1, n): |
| 36 | dp[0][i] = grid[0][i] + dp[0][i - 1] |
| 37 | for i in range(1, n): |
| 38 | dp[i][0] = grid[i][0] + dp[i - 1][0] |
| 39 | |
| 40 | for i in range(1, n): |
| 41 | for j in range(1, n): |
| 42 | dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]) |
| 43 | |
| 44 | return dp[-1][-1] |
| 45 | |
| 46 | |
| 47 | if __name__ == "__main__": |