82.py 574 B

12345678910111213141516171819202122
  1. #!/usr/bin/env python
  2. from copy import deepcopy
  3. m = [map(int, line.split(',')) for line in open('matrix.txt', 'r').readlines()]
  4. h, w = len(m), len(m[0])
  5. orig = deepcopy(m)
  6. def trypath(paths, *indices):
  7. try:
  8. paths.append(sum(orig[y][x] for x, y in indices))
  9. except IndexError:
  10. pass
  11. for c in xrange(1, w):
  12. for r in xrange(h):
  13. paths = []
  14. trypath(paths, (c - 1, r - 1), (c, r - 1))
  15. trypath(paths, (c - 1, r))
  16. trypath(paths, (c - 1, r + 1), (c, r + 1))
  17. m[r][c] += min(paths)
  18. print min(row[-1] for row in m)