{"id":61918,"date":"2024-04-27T16:56:25","date_gmt":"2024-04-27T16:56:25","guid":{"rendered":"https:\/\/www.askpython.com\/?p=61918"},"modified":"2025-04-10T20:31:04","modified_gmt":"2025-04-10T20:31:04","slug":"travelling-salesman-problem-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/travelling-salesman-problem-python","title":{"rendered":"Traveling Salesman Problem with Python: Greedy and Brute Force"},"content":{"rendered":"\n<p>Just imagine yourself as a delivery courier. You have to deliver multiple parcels to many different spots. You also aim to minimize the fuel costs and time of traveling to maximize profit. This generally creates confusion about where to deliver parcels first and which routes to take.<\/p>\n\n\n\n<p>In this article, we will learn about the famous problem of Travelling Salesman. We will solve this issue using Python programming language. We will also try to plot the best route to be taken and calculate the minimum distance to be traveled.<\/p>\n\n\n\n<p><strong><em>Recommended: <a href=\"https:\/\/www.askpython.com\/resources\/connected-health-exploring-iot-solutions-for-healthcare-transformation\">Connected Health: Exploring IoT Solutions for Healthcare Transformation<\/a><\/em><\/strong><\/p>\n\n\n\n<p><strong><em>Recommended: <a href=\"https:\/\/www.askpython.com\/python\/examples\/delivery-route-optimization-python\">Delivery Route Optimization using Python: A Step-by-Step Guide<\/a><\/em><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Solving the Traveling Salesman Problem with Python<\/h2>\n\n\n\n<p>The problem statement is that a salesman has to travel to the Indian cities of Mumbai, Delhi, Bangalore, Hyderabad, Ahmedabad, Chennai, Kolkata, Surat, Pune, and Jaipur to sell some products.<\/p>\n\n\n\n<p>The objective of the problem is to minimize the total distance travelled by the salesman.<\/p>\n\n\n\n<p>This describes our problem statement. Now let&#8217;s move on to how to solve this problem using Python programming language.<\/p>\n\n\n\n<p>We will look at two ways of solving the problem &#8211; using the Greedy algorithm and the Brute Force method ( this method is the most preferred one as it provides more optimal solutions ).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example Usage and Visualization of the Greedy Algorithm<\/h3>\n\n\n\n<p>Let us look at the code of the Simple Greedy algorithm.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport matplotlib.pyplot as plt\n\ndef distance(city1, city2):\n  # Replace this with your distance calculation function (e.g., Euclidean distance)\n  x1, y1 = city1\n  x2, y2 = city2\n  return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5\n\ndef tsp(cities):\n  visited = &#x5B;False] * len(cities)\n  current_city = 0\n\n  tour = &#x5B;]\n  total_distance = 0\n\n  for _ in range(len(cities)):\n    visited&#x5B;current_city] = True\n    tour.append(current_city)\n\n    next_city = None\n    min_distance = float(&#039;inf&#039;)  # Represents positive infinity\n\n    for i in range(len(cities)):\n      if visited&#x5B;i]:\n        continue\n\n      d = distance(cities&#x5B;current_city], cities&#x5B;i])\n      if d &lt; min_distance:\n        min_distance = d\n        next_city = i\n\n    current_city = next_city\n    total_distance += min_distance\n\n  return tour, total_distance\n\n# Example usage\ncities = &#x5B;(2, 4), (1, 8), (7, 1), (8, 5)]\n\ntour, total_distance = tsp(cities)\n\nprint(&quot;Tour:&quot;, tour)\nprint(&quot;Total Distance:&quot;, total_distance)\n\n# Plotting\nx_coords = &#x5B;cities&#x5B;i]&#x5B;0] for i in tour]\ny_coords = &#x5B;cities&#x5B;i]&#x5B;1] for i in tour]\nx_coords.append(x_coords&#x5B;0])  # Close the loop for plotting\ny_coords.append(y_coords&#x5B;0])\n\nplt.plot(x_coords, y_coords)\nplt.scatter(x_coords, y_coords, s=50, color=&#039;red&#039;)  # Plot cities as red dots\nplt.title(&quot;Traveling Salesman Problem - Greedy Algorithm&quot;)\nplt.show()\n\n<\/pre><\/div>\n\n\n<p>In the above example, we randomly input some coordinates and calculated the best route. Let us look at the output of this method.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"534\" height=\"435\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Travelling-Salesman-Greedy-algorithm.png\" alt=\"Travelling Salesman Greedy Algorithm\" class=\"wp-image-61919\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Travelling-Salesman-Greedy-algorithm.png 534w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Travelling-Salesman-Greedy-algorithm-300x244.png 300w\" sizes=\"auto, (max-width: 534px) 100vw, 534px\" \/><figcaption class=\"wp-element-caption\"><strong><em>Visualization of Greedy Algorithm Output<\/em><\/strong><\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"308\" height=\"37\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Travelling-Salesman-Greedy-algorithm-output.png\" alt=\"Travelling Salesman Greedy Algorithm Output\" class=\"wp-image-61920\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Travelling-Salesman-Greedy-algorithm-output.png 308w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Travelling-Salesman-Greedy-algorithm-output-300x36.png 300w\" sizes=\"auto, (max-width: 308px) 100vw, 308px\" \/><figcaption class=\"wp-element-caption\"><strong><em>Travelling Salesman Greedy Algorithm Output<\/em><\/strong><\/figcaption><\/figure>\n\n\n\n<p>Thus, according to the Greedy algorithm, we will travel to city 1 first, and cities 1,3,2 after that.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Brute Force Approach to the Traveling Salesman Problem<\/h3>\n\n\n\n<p>Let us look at the code of the Brute Force Method.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np\nimport itertools\nimport matplotlib.pyplot as plt\n\ndef calculate_distance(city1, city2):\n    return np.linalg.norm(np.array(city1) - np.array(city2))\n\ndef total_distance(route, distances):\n    total = 0\n    for i in range(len(route) - 1):\n        total += distances&#x5B;route&#x5B;i], route&#x5B;i+1]]\n    total += distances&#x5B;route&#x5B;-1], route&#x5B;0]]  # Complete the loop\n    return total\n\ndef brute_force_tsp(coords, city_names):\n    n = len(coords)\n    distances = np.zeros((n, n))\n    for i in range(n):\n        for j in range(i, n):\n            distances&#x5B;i, j] = distances&#x5B;j, i] = calculate_distance(coords&#x5B;i], coords&#x5B;j])\n\n    min_distance = float(&#039;inf&#039;)\n    min_route = None\n\n    for route in itertools.permutations(range(n)):\n        distance = total_distance(route, distances)\n        if distance &lt; min_distance:\n            min_distance = distance\n            min_route = route\n\n    min_route_names = &#x5B;city_names&#x5B;i] for i in min_route]\n    return min_route_names, min_distance\n\n# Generate random city coordinates and city names\nnp.random.seed(0)\ncity_names = &#x5B;&#039;Mumbai&#039;, &#039;Delhi&#039;, &#039;Bangalore&#039;, &#039;Hyderabad&#039;, &#039;Ahmedabad&#039;, &#039;Chennai&#039;, &#039;Kolkata&#039;, &#039;Surat&#039;, &#039;Pune&#039;, &#039;Jaipur&#039;]\nnum_cities = len(city_names)\ncoords_list = &#x5B;(np.random.randint(1, 100), np.random.randint(1, 100)) for _ in range(num_cities)]\n\n# Solve TSP using brute force\nbest_route, best_distance = brute_force_tsp(coords_list, city_names)\n\nprint(&#039;Best Route:&#039;, best_route)\nprint(&#039;Best Distance:&#039;, best_distance)\n\n# Plot the cities and the route\nplt.figure(figsize=(8, 6))\nplt.scatter(*zip(*coords_list), color=&#039;blue&#039;)\nfor i, city in enumerate(coords_list):\n    plt.text(city&#x5B;0], city&#x5B;1], city_names&#x5B;i], fontsize=12)\nfor i in range(len(best_route) - 1):\n    city1 = coords_list&#x5B;city_names.index(best_route&#x5B;i])]\n    city2 = coords_list&#x5B;city_names.index(best_route&#x5B;i+1])]\n    plt.plot(&#x5B;city1&#x5B;0], city2&#x5B;0]], &#x5B;city1&#x5B;1], city2&#x5B;1]], color=&#039;red&#039;, linewidth=1)\nplt.plot(&#x5B;coords_list&#x5B;city_names.index(best_route&#x5B;-1])]&#x5B;0], coords_list&#x5B;city_names.index(best_route&#x5B;0])]&#x5B;0]],\n         &#x5B;coords_list&#x5B;city_names.index(best_route&#x5B;-1])]&#x5B;1], coords_list&#x5B;city_names.index(best_route&#x5B;0])]&#x5B;1]], color=&#039;red&#039;, linewidth=1)  # Complete the loop\nplt.title(&#039;Brute Force TSP - Best Route&#039;)\nplt.xlabel(&#039;X Coordinate&#039;)\nplt.ylabel(&#039;Y Coordinate&#039;)\nplt.grid(True)\nplt.show()\n\n<\/pre><\/div>\n\n\n<p>Let us look at the output of the Brute Force method.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"719\" height=\"547\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Brute-Force-method.png\" alt=\"Brute Force Method\" class=\"wp-image-61921\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Brute-Force-method.png 719w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Brute-Force-method-300x228.png 300w\" sizes=\"auto, (max-width: 719px) 100vw, 719px\" \/><figcaption class=\"wp-element-caption\"><strong><em>Brute Force Method<\/em><\/strong><\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"34\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Brute-Force-method-output-1024x34.png\" alt=\"Brute Force Method Output\" class=\"wp-image-61922\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Brute-Force-method-output-1024x34.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Brute-Force-method-output-300x10.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Brute-Force-method-output-768x26.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Brute-Force-method-output.png 1457w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\"><strong><em>Brute Force Method Output<\/em><\/strong><\/figcaption><\/figure>\n\n\n\n<p>Thus, according to the Brute force method, the minimum distance is approximately 230 units.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Greedy Algorithm vs. Brute Force Method<\/h3>\n\n\n\n<p>The difference between the Greedy algorithm and the Brute Force method is that the Greedy algorithm builds up the solution step by step whereas in the Brute Force method, all the permutations of the solution are found and then the solution with minimum distance is selected.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Here you go! Now you know the Travelling Salesman Problem and how to solve it using Python. In this article, you learned about two methods of approach i.e. Greedy algorithm and Travelling Salesman problem.<\/p>\n\n\n\n<p>Hope you enjoyed reading it!<\/p>\n\n\n\n<p><strong><em>Recommended: <a href=\"https:\/\/www.askpython.com\/python\/examples\/backtracking-line-search-optimization\">Backtracking Line Search Algorithm for Unconstrained Optimization<\/a><\/em><\/strong><\/p>\n\n\n\n<p><strong><em>Recommended: <a href=\"https:\/\/www.askpython.com\/python\/examples\/python-large-integer-handling\">Large integer handling in Python (optimization)<\/a><\/em><\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Just imagine yourself as a delivery courier. You have to deliver multiple parcels to many different spots. You also aim to minimize the fuel costs and time of traveling to maximize profit. This generally creates confusion about where to deliver parcels first and which routes to take. In this article, we will learn about the [&hellip;]<\/p>\n","protected":false},"author":80,"featured_media":63881,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-61918","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/61918","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/80"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=61918"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/61918\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/63881"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=61918"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=61918"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=61918"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}