{"id":33446,"date":"2024-11-01T09:16:38","date_gmt":"2024-11-01T09:16:38","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=33446"},"modified":"2024-11-01T11:38:39","modified_gmt":"2024-11-01T11:38:39","slug":"java-coding-test-course-solving-the-traveling-salesman-problem","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/33446\/","title":{"rendered":"Java Coding Test Course, Solving the Traveling Salesman Problem"},"content":{"rendered":"<p>Hello, in this blog post, we will delve deeply into one of the frequently encountered problems in Java coding tests: the &#8220;Traveling Salesman Problem.&#8221; This problem is very useful for laying the foundations of graph theory and combinatorics, and it serves as a good example to apply various algorithmic techniques.<\/p>\n<h2>Problem Description<\/h2>\n<p>The Traveling Salesman Problem can be described as follows. The salesman is tasked with finding the shortest path that visits all the given cities and returns to the starting city. All cities are connected, and the distance between any two cities is provided. The goal is to complete the tour of the visited cities with the minimum cost.<\/p>\n<h3>Input<\/h3>\n<ul>\n<li>Number of cities N (2 \u2264 N \u2264 10)<\/li>\n<li>A cost matrix C of size N x N is provided. C[i][j] represents the cost of traveling from city i to city j. If it is not possible to travel from city i to j, C[i][j] is infinite.<\/li>\n<\/ul>\n<h3>Output<\/h3>\n<p>Output the minimum cost to visit all cities once and return to the starting city.<\/p>\n<h2>Problem Analysis<\/h2>\n<p>This problem is classified as an NP-hard problem, generally solvable with a complete search method. However, since N is limited to a maximum of 10, it can be solved efficiently using a bitmask technique with dynamic programming (DP). By using a bitmask, we can represent the visit status of each city as bits, allowing us to calculate the minimum cost for all possible paths.<\/p>\n<h2>Algorithm Design<\/h2>\n<p>The basic idea for solving the problem is as follows:<\/p>\n<ol>\n<li>Use a bitmask to indicate the visit state of each city.<\/li>\n<li>Recursively explore all possible paths while calculating the minimum path.<\/li>\n<li>Use memoization to store already calculated minimum costs to avoid redundant calculations.<\/li>\n<\/ol>\n<h3>Key Variables<\/h3>\n<ul>\n<li><strong>N<\/strong>: Number of cities<\/li>\n<li><strong>C[][]<\/strong>: Cost matrix<\/li>\n<li><strong>cache<\/strong>: Array for memoization<\/li>\n<li><strong>allVisited<\/strong>: Bitmask to check if all cities have been visited<\/li>\n<li><strong>start<\/strong>: Starting city<\/li>\n<\/ul>\n<h2>Java Code Implementation<\/h2>\n<p>The code below implements the Traveling Salesman Problem according to the given algorithm. Check how each step progresses through the code.<\/p>\n<pre>\n<code>\nimport java.util.Arrays;\n\npublic class TravelingSalesman {\n    \n    static int N; \/\/ Number of cities\n    static int[][] C; \/\/ Cost matrix\n    static int[][] cache; \/\/ Array for memoization\n    static final int INF = Integer.MAX_VALUE; \/\/ Infinite value\n\n    public static void main(String[] args) {\n        \/\/ Example: Number of cities N = 4\n        N = 4; \n        C = new int[][]{\n            {0, 10, 15, 20},\n            {5, 0, 9, 10},\n            {6, 13, 0, 12},\n            {8, 8, 9, 0}\n        };\n\n        \/\/ Initialize the memoization array\n        cache = new int[1 << N][N];\n        for (int i = 0; i < (1 << N); i++) {\n            Arrays.fill(cache[i], -1);\n        }\n\n        int result = tsp(1, 0); \/\/ Start from the initial city 0 having visited all cities\n        System.out.println(\"Minimum cost: \" + result);\n    }\n\n    static int tsp(int visited, int pos) {\n        \/\/ Base case: when all cities have been visited\n        if (visited == (1 << N) - 1) {\n            return C[pos][0] == 0 ? INF : C[pos][0]; \/\/ Cost to return to the starting city\n        }\n\n        \/\/ If already computed\n        if (cache[visited][pos] != -1) {\n            return cache[visited][pos];\n        }\n\n        int answer = INF;\n\n        \/\/ Check all cities\n        for (int city = 0; city < N; city++) {\n            \/\/ If the city hasn't been visited yet\n            if ((visited &#038; (1 << city)) == 0 &#038;&#038; C[pos][city] != 0) {\n                int newVisited = visited | (1 << city);\n                int newCost = C[pos][city] + tsp(newVisited, city);\n                answer = Math.min(answer, newCost);\n            }\n        }\n\n        return cache[visited][pos] = answer; \/\/ Store the minimum cost\n    }\n}\n<\/code>\n<\/pre>\n<h2>Code Explanation<\/h2>\n<ol>\n<li><strong>Main Method:<\/strong> Initializes the number of cities and the cost matrix with the example, calls the TSP function, and outputs the result.<\/li>\n<li><strong>tsp Method:<\/strong> Recursively calculates the minimum cost based on the bitmask and current city information.<\/li>\n<li><strong>Base Case:<\/strong> When all cities have been visited, returns the cost to return to the starting city.<\/li>\n<li><strong>Memoization:<\/strong> Already computed states are stored in the cache array and reused as needed to enhance efficiency.<\/li>\n<\/ol>\n<h2>Results<\/h2>\n<p>The above code calculates the minimum cost for the provided cities and cost matrix. The output is the minimum cost to visit all cities and return to the starting city. You can input your own cost matrix using this code and check the results, which will help you understand the flow of the algorithm.<\/p>\n<h2>Conclusion<\/h2>\n<p>Through this tutorial, we learned how to solve the Traveling Salesman Problem using dynamic programming and bitmasks. This problem frequently appears in coding tests and will significantly aid in learning fundamental algorithmic techniques to tackle such challenges. Like other algorithm problems, there are multiple ways to approach the problem. Try various solutions to enhance your algorithm skills.<\/p>\n<p>Stay tuned for our next post, where we will cover another problem. If you have any questions or comments, please leave them below. Thank you!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello, in this blog post, we will delve deeply into one of the frequently encountered problems in Java coding tests: the &#8220;Traveling Salesman Problem.&#8221; This problem is very useful for laying the foundations of graph theory and combinatorics, and it serves as a good example to apply various algorithmic techniques. Problem Description The Traveling Salesman &hellip; <a href=\"https:\/\/atmokpo.com\/w\/33446\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Java Coding Test Course, Solving the Traveling Salesman Problem&#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":[139],"tags":[],"class_list":["post-33446","post","type-post","status-publish","format-standard","hentry","category-java-coding-test"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Java Coding Test Course, Solving the Traveling Salesman Problem - \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\/33446\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Coding Test Course, Solving the Traveling Salesman Problem - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"Hello, in this blog post, we will delve deeply into one of the frequently encountered problems in Java coding tests: the &#8220;Traveling Salesman Problem.&#8221; This problem is very useful for laying the foundations of graph theory and combinatorics, and it serves as a good example to apply various algorithmic techniques. Problem Description The Traveling Salesman &hellip; \ub354 \ubcf4\uae30 &quot;Java Coding Test Course, Solving the Traveling Salesman Problem&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/33446\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:16:38+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:38:39+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\/33446\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33446\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Java Coding Test Course, Solving the Traveling Salesman Problem\",\"datePublished\":\"2024-11-01T09:16:38+00:00\",\"dateModified\":\"2024-11-01T11:38:39+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33446\/\"},\"wordCount\":554,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Java Coding Test\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/33446\/\",\"url\":\"https:\/\/atmokpo.com\/w\/33446\/\",\"name\":\"Java Coding Test Course, Solving the Traveling Salesman Problem - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:16:38+00:00\",\"dateModified\":\"2024-11-01T11:38:39+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33446\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/33446\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/33446\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Coding Test Course, Solving the Traveling Salesman Problem\"}]},{\"@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":"Java Coding Test Course, Solving the Traveling Salesman Problem - \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\/33446\/","og_locale":"ko_KR","og_type":"article","og_title":"Java Coding Test Course, Solving the Traveling Salesman Problem - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"Hello, in this blog post, we will delve deeply into one of the frequently encountered problems in Java coding tests: the &#8220;Traveling Salesman Problem.&#8221; This problem is very useful for laying the foundations of graph theory and combinatorics, and it serves as a good example to apply various algorithmic techniques. Problem Description The Traveling Salesman &hellip; \ub354 \ubcf4\uae30 \"Java Coding Test Course, Solving the Traveling Salesman Problem\"","og_url":"https:\/\/atmokpo.com\/w\/33446\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:16:38+00:00","article_modified_time":"2024-11-01T11:38:39+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\/33446\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/33446\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Java Coding Test Course, Solving the Traveling Salesman Problem","datePublished":"2024-11-01T09:16:38+00:00","dateModified":"2024-11-01T11:38:39+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/33446\/"},"wordCount":554,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Java Coding Test"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/33446\/","url":"https:\/\/atmokpo.com\/w\/33446\/","name":"Java Coding Test Course, Solving the Traveling Salesman Problem - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:16:38+00:00","dateModified":"2024-11-01T11:38:39+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/33446\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/33446\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/33446\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Java Coding Test Course, Solving the Traveling Salesman Problem"}]},{"@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\/33446","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=33446"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33446\/revisions"}],"predecessor-version":[{"id":33447,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33446\/revisions\/33447"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=33446"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=33446"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=33446"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}