NOTE: This problem is a significantly more challenging version of Problem 81.
In the by matrix below, the minimal path sum from
the top left to the bottom right, by moving left, right, up, and down,
is indicated in bold red and is equal to .
Find the minimal path sum from the top left to the bottom right by
moving left, right, up, and down in matrix.txt (right click and
"Save Link/Target As..."), a 31K text file containing an by matrix.
ls = open('p081_matrix.txt', 'r').readlines() n = len(ls) a = [] for i inrange(n): b = [int(x) for x in ls[i][:-1].split(',')] a.append(b) g = nx.DiGraph() d = [[-1, 0], [1, 0], [0, -1], [0, 1]]
for i inrange(n): for j inrange(n): for dx, dy in d: x, y = i + dx, j + dy if0 <= x < n and0 <= y < n: g.add_edge((i, j), (x, y), weight=a[x][y]) ans = nx.dijkstra_path_length(g, (0, 0), (n - 1, n - 1)) + a[0][0] print(ans)