{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class City:\n", " def __init__(self, id, links = []):\n", " self.id = id\n", " self.links = links" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "City1 = City(1, [(2, 10), (3, 15), (4, 20)])\n", "City2 = City(2, [(1, 10), (3, 35), (4, 25)])\n", "City3 = City(3, [(1, 15), (2, 35), (4, 30)])\n", "City4 = City(4, [(1, 20), (2, 25), (3, 30)])\n", "\n", "cities = [City1, City2, City3, City4]" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [], "source": [ "def findShortestPath(curr_id, visited_ids, cities, cost = 0):\n", " curr_index = curr_id - 1\n", "\n", " if len(visited_ids) == len(cities):\n", " for link in cities[curr_index].links:\n", " if link[0] == visited_ids[0]:\n", " return (visited_ids + [visited_ids[0]], cost + link[1])\n", "\n", " curr_cost = 0\n", " min_cost = ((), 1000)\n", " for link in cities[curr_index].links:\n", " if link[0] not in visited_ids:\n", " curr_cost = findShortestPath(link[0], visited_ids + [link[0]], cities, cost + link[1])\n", " if curr_cost[1] < min_cost[1]:\n", " min_cost = curr_cost\n", "\n", " return min_cost\n", " " ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "([1, 2, 4, 3, 1], 80)\n", "([2, 1, 3, 4, 2], 80)\n", "([3, 1, 2, 4, 3], 80)\n", "([4, 2, 1, 3, 4], 80)\n" ] } ], "source": [ "for i in range(1, len(cities) + 1):\n", " print(findShortestPath(i, [i], cities))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3.9.7 64-bit", "language": "python", "name": "python3" }, "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.9.7" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "916dbcbb3f70747c44a77c7bcd40155683ae19c65e1c03b4aa3499c5328201f1" } } }, "nbformat": 4, "nbformat_minor": 2 }