19/40
Part 4 of 7 · A park with no cyclesLearn and do
Bottom-up in topological order has no depth at all
Kahn's algorithm from the topological-sort lesson gives the order. Read a stretch from upper down to lower as the arrow from a prerequisite to the task that needs it. With park_order(stretches, start) returning below and that order, the pass from the start is a few lines:
def best_from_start(stretches, start, exits):
below, order = park_order(stretches, start)
# -inf: no route from start reaches it
best = dict.fromkeys(order, -math.inf)
best[start] = 0
# every stretch into j comes from earlier in the order
for j in order:
for lower, score in below[j]:
best[lower] = max(best[lower], best[j] + score)
reached = [best[e] for e in exits if best.get(e, -math.inf) != -math.inf]
return max(reached) if reached else None
print(park_order(PARK, "top")[1])
print(best_from_start(PARK, "top", EXITS))
['top', 'birch', 'ash', 'dell', 'cliff', 'falls', 'end']
12
In the editor, write park_order(stretches, start) with Kahn's algorithm. It prints the park's order, then two edges.