{ "cells": [ { "cell_type": "markdown", "id": "bcfe0c52", "metadata": {}, "source": [ "# [Path Sum: Three Ways](https://projecteuler.net/problem=82)\n", "\n", "This is the same matrix as [problem 81](https://projecteuler.net/problem=81)." ] }, { "cell_type": "code", "execution_count": 1, "id": "098b70b9", "metadata": {}, "outputs": [], "source": [ "with open(\"txt/0082_matrix.txt\") as f:\n", " mat = matrix((int(n) for n in line.split(',')) for line in f)" ] }, { "cell_type": "markdown", "id": "aaf2f803", "metadata": {}, "source": [ "We can reuse our solution from problem 81 as well, with some slight modifications.\n", "1. Instead of our queue initially containing only the top-left entry of the matrix, it will initially hold *all* the entries from the first column.\n", "2. Additionally, instead of checking if we've reached the bottom-right entry, we'll stop on reaching *any entry* in the last column.\n", "3. Finally, when adding new entries to the queue, we'll add the entry *above* our current entry, along with the entries to the right and below, as before." ] }, { "cell_type": "code", "execution_count": 2, "id": "3b7872ef", "metadata": {}, "outputs": [], "source": [ "import heapq\n", "\n", "def minimal_path_sum(mat):\n", " m, n = mat.dimensions()\n", " \n", " destinations = {(i, n - 1) for i in range(0, m)}\n", " visited = set()\n", " queue = [(0, (i, 0)) for i in range(0, m)]\n", " while queue != []:\n", " cost, (i, j) = heapq.heappop(queue)\n", " \n", " if (i, j) in visited:\n", " continue\n", " visited.add((i, j))\n", " \n", " cost += mat[i, j]\n", " \n", " if (i, j) in destinations:\n", " break\n", " \n", " if i - 1 >= 0:\n", " heapq.heappush(queue, (cost, (i - 1, j)))\n", " \n", " if i + 1 < m:\n", " heapq.heappush(queue, (cost, (i + 1, j)))\n", " \n", " if j + 1 < n:\n", " heapq.heappush(queue, (cost, (i, j + 1)))\n", " \n", " return cost" ] }, { "cell_type": "code", "execution_count": 3, "id": "62aba318", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "260324" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "minimal_path_sum(mat)" ] }, { "cell_type": "markdown", "id": "db7b11ca", "metadata": {}, "source": [ "#### Copyright (C) 2025 filifa\n", "\n", "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)." ] } ], "metadata": { "kernelspec": { "display_name": "SageMath 9.5", "language": "sage", "name": "sagemath" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.2" } }, "nbformat": 4, "nbformat_minor": 5 }