Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. # The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any
  2. # cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal to 994.
  3. #
  4. # Find the minimal path sum, in matrix.txt (right click and "Save Link/Target As..."), a 31K text file containing a
  5. # 80 by 80 matrix, from the left column to the right column.
  6.  
  7.  
  8. from copy import deepcopy
  9.  
  10. with open("p082_matrix.txt") as f:
  11. lines = f.readlines()
  12.  
  13. matrix = [[int(x) for x in line.strip().split(",")] for line in lines]
  14.  
  15. initial_matrix = deepcopy(matrix)
  16.  
  17. n = len(matrix)
  18.  
  19. for j in range(1, n):
  20. matrix[0][j] += matrix[0][j - 1]
  21. for i in range(1, n - 1):
  22. matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1])
  23. matrix[n - 1][j] += min(matrix[n - 2][j], matrix[n - 1][j - 1])
  24. for i in reversed(range(0, n - 1)):
  25. matrix[i][j] = min(matrix[i][j], matrix[i + 1][j] + initial_matrix[i][j])
  26.  
  27. print(min(matrix[j][-1] for j in range(len(matrix))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement