Maximum path sum I
First read the problem description.
This problem is very similar to Problem 15. We build a DAG and then find the longest path taking in consideration the weight of each node. This algorithm solves Problem 67 too.
import networkx as nx
from urllib.request import urlopen
def read_triangle(file):
= ""
triangle_data try:
with open(file) as f:
= f.read()
triangle_data except FileNotFoundError:
with urlopen("https://xojoc.pw/challenges/euler/" + file) as response:
= response.read().decode()
triangle_data
return [[int(n) for n in line.split(' ')] for line in triangle_data[:-1].split('\n')]
def build_graph(triangle):
= nx.DiGraph()
g
def T(n):
return n * (n + 1) // 2
def i(row, col):
return 1 + T(row) + col
for r in range(len(triangle)):
for c in range(r + 1):
=triangle[r][c])
g.add_node(i(r, c), weight
for r in range(len(triangle)-1):
for c in range(r+1):
+ 1, c))
g.add_edge(i(r, c), i(r + 1, c + 1))
g.add_edge(i(r, c), i(r
return g
def longest_path(g):
= list(nx.topological_sort(g))
sorted_nodes = sorted_nodes[0]
first_node = nx.get_node_attributes(g, 'weight')
node_weights = {}
cache for n in reversed(sorted_nodes):
= 0
max_weight for s in g.successors(n):
= max(cache[s], max_weight)
max_weight = node_weights[n] + max_weight
cache[n] return cache[first_node]
for f in ["18.txt", "67.txt"]:
= read_triangle(f)
triangle = build_graph(triangle)
g print(longest_path(g))
1074
7273
Source code of the solution(s):