"# [Path Sum: Two Ways](https://projecteuler.net/problem=81)\n",
"\n",
"First things first, we'll read in the matrix."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "ef846cb1",
"metadata": {},
"outputs": [],
"source": [
"with open(\"txt/0081_matrix.txt\") as f:\n",
" mat = matrix((int(n) for n in line.split(',')) for line in f)"
]
},
{
"cell_type": "markdown",
"id": "af2036f4",
"metadata": {},
"source": [
"This problem is fundamentally a [shortest path problem](https://en.wikipedia.org/wiki/Shortest_path_problem), a well-studied problem with lots of algorithms to choose from. We'll employ a variant of [Dijkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm) - we would need a different algorithm if the matrix had negative entries.\n",
"\n",
"In short, this algorithm starts with the top-left entry of the matrix and adds its neighbors below and right of it to a search queue. The queue emits entries in the order of smallest path sum from the top-left entry, so the first time we visit an entry, we know the path taken to it is its minimal path. This means when we visit the bottom-right entry, we'll have computed its minimal path and can exit. We also keep track of nodes we've already visited so we don't waste time re-visiting them.\n",
"\n",
"Note that we could improve this even further by implementing a [Fibonacci heap](https://en.wikipedia.org/wiki/Fibonacci_heap) for our priority queue, but using a binary heap - [built-in to Python!](https://docs.python.org/3/library/heapq.html) - is plenty fast for this problem."
"This work is licensed under the [Creative Commons Attribution-ShareAlike 4.0 International license](https://creativecommons.org/licenses/by-sa/4.0/) and the [BSD Zero Clause license](https://spdx.org/licenses/0BSD.html)."