{"id":34810,"date":"2024-11-01T09:32:14","date_gmt":"2024-11-01T09:32:14","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=34810"},"modified":"2024-11-01T11:26:26","modified_gmt":"2024-11-01T11:26:26","slug":"swift-coding-test-course-creating-a-traveling-salesman-route","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/34810\/","title":{"rendered":"Swift Coding Test Course, Creating a Traveling Salesman Route"},"content":{"rendered":"<p><body><\/p>\n<article>\n<header>\n<p><strong>Hello!<\/strong> In this tutorial, we will cover the &#8220;Travelling Salesman Problem,&#8221; a common algorithm problem encountered in coding tests, using the Swift language. This problem requires an understanding of graph theory, combinatorial optimization, and overall algorithm problem-solving.<\/p>\n<\/header>\n<section>\n<h2>Problem Definition<\/h2>\n<p>The Travelling Salesman Problem (TSP) involves finding the shortest route for a salesman to visit n cities exactly once and return to the starting city, given the distances between each pair of cities. The inputs consist of the number of cities n and the distance matrix between those cities.<\/p>\n<h3>Input Format<\/h3>\n<ul>\n<li>First line: Number of cities n (1 \u2264 n \u2264 10)<\/li>\n<li>Next n lines: Distance matrix, where the i-th line contains the distances from the i-th city to each city (A[i][j] is the distance from city i to city j)<\/li>\n<\/ul>\n<h3>Output Format<\/h3>\n<p>Output the length of the shortest route that visits all cities and returns to the starting city.<\/p>\n<\/section>\n<section>\n<h2>Problem-Solving Approach<\/h2>\n<p>This problem belongs to the NP-Hard category, so it can be solved using dynamic programming techniques combined with pruning. This method allows us to only choose the least costly paths while constructing routes, rather than exploring all possible paths.<\/p>\n<h3>Step 1: Data Structure Design<\/h3>\n<p>First, declare a 2D array to store distance information between cities. Additionally, declare an array to check which cities have been visited and a variable to store the total distance so far.<\/p>\n<h3>Step 2: Using Bitmask and Recursive Functions<\/h3>\n<p>Use bitmasking to represent whether each city has been visited. Every time we move to the next city via a recursive function, check off the visited cities and calculate the distance of the path taken once all cities have been visited and the route returns to the starting city. Since visited cities can be easily represented with a bitmask, they can be processed efficiently.<\/p>\n<h3>Step 3: Finding the Optimal Route<\/h3>\n<p>Instead of exploring all possible paths, proceed by calculating the minimum distance among the currently selected paths. If the given path has visited all cities, compare it with the previous distance to update the minimum value.<\/p>\n<\/section>\n<section>\n<h2>Swift Code Implementation<\/h2>\n<p>Below is the code for finding the travelling salesman route using Swift.<\/p>\n<pre><code>\nlet INF = Int.max\nvar dist: [[Int]] = []\nvar n = 0\nvar dp: [[Int]] = []\nvar visited: Int = 0\nvar ans: Int = INF\n\nfunc tsp(pos: Int, visited: Int) -> Int {\n    if visited == (1 << n) - 1 {\n        return dist[pos][0] != 0 ? dist[pos][0] : INF\n    }\n    \n    if dp[pos][visited] != -1 {\n        return dp[pos][visited]\n    }\n    \n    var minimum = INF\n    for city in 0..<n {\n        let new_visited = visited | (1 << city)\n        let new_dist = dist[pos][city]\n        minimum = min(minimum, new_dist + tsp(pos: city, visited: new_visited))\n    }\n    \n    dp[pos][visited] = minimum\n    return minimum\n}\n\nfunc findMinimumRoute() -> Int {\n    visited = 1 \/\/ start from city 0\n    dp = Array(repeating: Array(repeating: -1, count: 1 << n), count: n)\n    let minimumDistance = tsp(pos: 0, visited: visited)\n    return minimumDistance\n}\n\n\/\/ Example distance matrix\ndist = [\n    [0, 10, 15, 20],\n    [10, 0, 35, 25],\n    [15, 35, 0, 30],\n    [20, 25, 30, 0]\n]\nn = dist.count\n\nlet result = findMinimumRoute()\nprint(\"The length of the minimum route is \\(result).\")\n<\/code><\/pre>\n<\/section>\n<section>\n<h2>Code Analysis and Functionality<\/h2>\n<p>This code uses bitmasking to check visit completion and recursively explores possible routes to calculate the minimum route. Every time a city is visited, the total distance is updated, and it finally returns the distance of the route that goes back to the starting city after visiting all cities.<\/p>\n<h3>1. Initializing the dp Array<\/h3>\n<p>The dp array stores the minimum route distances based on each city and visit status. Initially, all elements are set to -1 to indicate an unvisited state.<\/p>\n<h3>2. Recursive Function tsp()<\/h3>\n<p>The recursive function tsp() takes the current position (pos) and the visited city bitmask (visited) as parameters to compute the optimal route. If all cities have been visited, it compares the cost of returning to the starting city and returns the minimum value.<\/p>\n<h3>3. Route Calculation<\/h3>\n<p>Bitmasking checks for cities that have not yet been visited and calculates the move to the next city, exploring all possibilities. The distances between cities are accumulated by calling `tsp()` for the entire route distance.<\/p>\n<\/section>\n<section>\n<h2>Conclusion<\/h2>\n<p>In this tutorial, we explored the Travelling Salesman Problem in detail. We discussed how to efficiently solve it using bitmasking and DP while writing a Swift code. I hope this problem, which frequently appears in coding tests, enhances your algorithm problem-solving skills.<\/p>\n<p>I wish you the best in your coding journey! Thank you.<\/p>\n<\/section>\n<\/article>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello! In this tutorial, we will cover the &#8220;Travelling Salesman Problem,&#8221; a common algorithm problem encountered in coding tests, using the Swift language. This problem requires an understanding of graph theory, combinatorial optimization, and overall algorithm problem-solving. Problem Definition The Travelling Salesman Problem (TSP) involves finding the shortest route for a salesman to visit n &hellip; <a href=\"https:\/\/atmokpo.com\/w\/34810\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Swift Coding Test Course, Creating a Traveling Salesman Route&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[129],"tags":[],"class_list":["post-34810","post","type-post","status-publish","format-standard","hentry","category-swift-coding-test"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Swift Coding Test Course, Creating a Traveling Salesman Route - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/34810\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Swift Coding Test Course, Creating a Traveling Salesman Route - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"Hello! In this tutorial, we will cover the &#8220;Travelling Salesman Problem,&#8221; a common algorithm problem encountered in coding tests, using the Swift language. This problem requires an understanding of graph theory, combinatorial optimization, and overall algorithm problem-solving. Problem Definition The Travelling Salesman Problem (TSP) involves finding the shortest route for a salesman to visit n &hellip; \ub354 \ubcf4\uae30 &quot;Swift Coding Test Course, Creating a Traveling Salesman Route&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/34810\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:32:14+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:26:26+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"2\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/34810\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34810\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Swift Coding Test Course, Creating a Traveling Salesman Route\",\"datePublished\":\"2024-11-01T09:32:14+00:00\",\"dateModified\":\"2024-11-01T11:26:26+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34810\/\"},\"wordCount\":580,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Swift Coding Test\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/34810\/\",\"url\":\"https:\/\/atmokpo.com\/w\/34810\/\",\"name\":\"Swift Coding Test Course, Creating a Traveling Salesman Route - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:32:14+00:00\",\"dateModified\":\"2024-11-01T11:26:26+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34810\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/34810\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/34810\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Swift Coding Test Course, Creating a Traveling Salesman Route\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Swift Coding Test Course, Creating a Traveling Salesman Route - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/34810\/","og_locale":"ko_KR","og_type":"article","og_title":"Swift Coding Test Course, Creating a Traveling Salesman Route - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"Hello! In this tutorial, we will cover the &#8220;Travelling Salesman Problem,&#8221; a common algorithm problem encountered in coding tests, using the Swift language. This problem requires an understanding of graph theory, combinatorial optimization, and overall algorithm problem-solving. Problem Definition The Travelling Salesman Problem (TSP) involves finding the shortest route for a salesman to visit n &hellip; \ub354 \ubcf4\uae30 \"Swift Coding Test Course, Creating a Traveling Salesman Route\"","og_url":"https:\/\/atmokpo.com\/w\/34810\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:32:14+00:00","article_modified_time":"2024-11-01T11:26:26+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"2\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/34810\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/34810\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Swift Coding Test Course, Creating a Traveling Salesman Route","datePublished":"2024-11-01T09:32:14+00:00","dateModified":"2024-11-01T11:26:26+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/34810\/"},"wordCount":580,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Swift Coding Test"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/34810\/","url":"https:\/\/atmokpo.com\/w\/34810\/","name":"Swift Coding Test Course, Creating a Traveling Salesman Route - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:32:14+00:00","dateModified":"2024-11-01T11:26:26+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/34810\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/34810\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/34810\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Swift Coding Test Course, Creating a Traveling Salesman Route"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34810","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=34810"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34810\/revisions"}],"predecessor-version":[{"id":34811,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34810\/revisions\/34811"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=34810"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=34810"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=34810"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}