{"id":34934,"date":"2024-11-01T09:33:47","date_gmt":"2024-11-01T09:33:47","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=34934"},"modified":"2024-11-01T11:45:40","modified_gmt":"2024-11-01T11:45:40","slug":"kotlin-coding-test-course-finding-the-k-th-shortest-path","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/34934\/","title":{"rendered":"Kotlin Coding Test Course: Finding the K-th Shortest Path"},"content":{"rendered":"<p><body><\/p>\n<p>In this tutorial, we will solve the algorithm problem of finding the K-th shortest path using Kotlin. This problem utilizes shortest path algorithms, which are an important part of graph theory. Calculating the K-th shortest path in a given graph is often considered a complex problem, but with the appropriate algorithms and data structures, it can be solved efficiently.<\/p>\n<h2>Problem Description<\/h2>\n<p>The problem is to find the K-th shortest path between two points A and B when a graph is given. The weights of the paths are positive, and K is set to be 1 or greater. Paths may overlap, and K starts from 1. Thus, K=1 refers to the shortest path, while K=2 refers to the second shortest path. If the K-th path does not exist, &#8220;NO PATH&#8221; should be output.<\/p>\n<div class=\"example\">\n<h3>Example<\/h3>\n<p><strong>Input:<\/strong><\/p>\n<pre>\n4 5 2\n1 2 1\n1 3 4\n2 3 2\n2 4 6\n3 4 3\n        <\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre>\n3\n        <\/pre>\n<p>In the above example, &#8216;4&#8217; is the number of vertices, &#8216;5&#8217; is the number of edges, and &#8216;2&#8217; is the value of K. Then, the starting point, endpoint, and weight of each edge are provided. In this case, the distance of the second shortest path from 1 to 4 is 3.<\/p>\n<\/div>\n<h2>Approach to Solve the Problem<\/h2>\n<p>To solve this problem, we will use Dijkstra&#8217;s algorithm along with a priority queue to find the K-th shortest path. This approach can be extended to find multiple shortest paths from a single starting point. The basic idea is to repeat the process of finding the shortest path K times and store the K-th length at each step.<\/p>\n<h3>1. Set up Data Structures<\/h3>\n<p>First, we need to set up a data structure to store the K-th shortest path information for each node. We can use a 2D array for this purpose. The index of each array represents the node ID, and the second index represents the K-th path.<\/p>\n<pre>\nval distance = Array(n + 1) { IntArray(k + 1) { Int.MAX_VALUE } }\n    <\/pre>\n<h3>2. Build the Graph<\/h3>\n<p>The graph will be represented in the form of an adjacency list. To do this, we will store the connected vertices and weights for each vertex. We will construct the graph from the input.<\/p>\n<pre>\nval graph = mutableListOf<mutableList<Edge>>()\nfor (i in 0 until n + 1) {\n    graph.add(mutableListOf())\n}\nfor (i in 0 until m) {\n    val (u, v, w) = readLine()!!.split(\" \").map { it.toInt() }\n    graph[u].add(Edge(v, w))\n}\n    <\/pre>\n<h3>3. Algorithm to Find the K-th Shortest Path<\/h3>\n<p>We will use a priority queue to find the shortest path. We will update the distance while adding each path to the queue. The distance array will be managed appropriately to store the K-th shortest path.<\/p>\n<pre>\nval queue = PriorityQueue<Edge>(compareBy { it.weight })\ndistance[start][0] = 0\nqueue.add(Edge(start, 0))\n\nwhile (queue.isNotEmpty()) {\n    val current = queue.poll()\n    val currentNode = current.node\n    val currentWeight = current.weight\n    \n    for (edge in graph[currentNode]) {\n        val nextNode = edge.node\n        val newWeight = currentWeight + edge.weight\n        if (distance[nextNode][k - 1] > newWeight) {\n            distance[nextNode].sort()\n            distance[nextNode][k - 1] = newWeight\n            queue.add(Edge(nextNode, newWeight))\n        }\n    }\n}\n    <\/pre>\n<h3>4. Output the Result<\/h3>\n<p>Finally, we will output the distance of the K-th shortest path. If the K-th path does not exist, we will output &#8220;NO PATH&#8221;.<\/p>\n<pre>\nif (distance[end][k - 1] == Int.MAX_VALUE) {\n    println(\"NO PATH\")\n} else {\n    println(distance[end][k - 1])\n}\n    <\/pre>\n<h2>Full Code<\/h2>\n<pre class=\"algorithm\">\nfun main() {\n    val (n, m, k) = readLine()!!.split(\" \").map { it.toInt() }\n    val graph = mutableListOf<mutableList<Edge>>()\n    \n    for (i in 0..n) {\n        graph.add(mutableListOf())\n    }\n    \n    for (i in 0 until m) {\n        val (u, v, w) = readLine()!!.split(\" \").map { it.toInt() }\n        graph[u].add(Edge(v, w))\n    }\n    \n    val distance = Array(n + 1) { IntArray(k + 1) { Int.MAX_VALUE } }\n    val queue = PriorityQueue<Edge>(compareBy { it.weight })\n    \n    distance[1][0] = 0\n    queue.add(Edge(1, 0))\n\n    while (queue.isNotEmpty()) {\n        val current = queue.poll()\n        val currentNode = current.node\n        val currentWeight = current.weight\n        \n        for (edge in graph[currentNode]) {\n            val nextNode = edge.node\n            val newWeight = currentWeight + edge.weight\n\n            if (distance[nextNode][k - 1] > newWeight) {\n                distance[nextNode].sort()\n                distance[nextNode][k - 1] = newWeight\n                queue.add(Edge(nextNode, newWeight))\n            }\n        }\n    }\n    \n    if (distance[n][k - 1] == Int.MAX_VALUE) {\n        println(\"NO PATH\")\n    } else {\n        println(distance[n][k - 1])\n    }\n}\n\ndata class Edge(val node: Int, val weight: Int)\n    <\/pre>\n<h2>Conclusion<\/h2>\n<p>Finding the K-th shortest path is a graph problem with various algorithmic approaches possible. In the above example, we explained how to find the K-th shortest path by modifying Dijkstra&#8217;s algorithm. In practice, a variety of algorithms or optimization techniques can be applied, and it is important to choose the right algorithm depending on the problem.<\/p>\n<p>The K-th shortest path finding problem we learned in this tutorial is often encountered in coding interviews, so it is advisable to improve your skills through various practice problems.<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we will solve the algorithm problem of finding the K-th shortest path using Kotlin. This problem utilizes shortest path algorithms, which are an important part of graph theory. Calculating the K-th shortest path in a given graph is often considered a complex problem, but with the appropriate algorithms and data structures, it &hellip; <a href=\"https:\/\/atmokpo.com\/w\/34934\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Kotlin Coding Test Course: Finding the K-th Shortest Path&#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":[106],"tags":[],"class_list":["post-34934","post","type-post","status-publish","format-standard","hentry","category----en"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Kotlin Coding Test Course: Finding the K-th Shortest Path - \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\/34934\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Kotlin Coding Test Course: Finding the K-th Shortest Path - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"In this tutorial, we will solve the algorithm problem of finding the K-th shortest path using Kotlin. This problem utilizes shortest path algorithms, which are an important part of graph theory. Calculating the K-th shortest path in a given graph is often considered a complex problem, but with the appropriate algorithms and data structures, it &hellip; \ub354 \ubcf4\uae30 &quot;Kotlin Coding Test Course: Finding the K-th Shortest Path&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/34934\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:33:47+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:45:40+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=\"4\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/34934\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34934\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Kotlin Coding Test Course: Finding the K-th Shortest Path\",\"datePublished\":\"2024-11-01T09:33:47+00:00\",\"dateModified\":\"2024-11-01T11:45:40+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34934\/\"},\"wordCount\":495,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Kotlin coding test\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/34934\/\",\"url\":\"https:\/\/atmokpo.com\/w\/34934\/\",\"name\":\"Kotlin Coding Test Course: Finding the K-th Shortest Path - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:33:47+00:00\",\"dateModified\":\"2024-11-01T11:45:40+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34934\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/34934\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/34934\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Kotlin Coding Test Course: Finding the K-th Shortest Path\"}]},{\"@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":"Kotlin Coding Test Course: Finding the K-th Shortest Path - \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\/34934\/","og_locale":"ko_KR","og_type":"article","og_title":"Kotlin Coding Test Course: Finding the K-th Shortest Path - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"In this tutorial, we will solve the algorithm problem of finding the K-th shortest path using Kotlin. This problem utilizes shortest path algorithms, which are an important part of graph theory. Calculating the K-th shortest path in a given graph is often considered a complex problem, but with the appropriate algorithms and data structures, it &hellip; \ub354 \ubcf4\uae30 \"Kotlin Coding Test Course: Finding the K-th Shortest Path\"","og_url":"https:\/\/atmokpo.com\/w\/34934\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:33:47+00:00","article_modified_time":"2024-11-01T11:45:40+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":"4\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/34934\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/34934\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Kotlin Coding Test Course: Finding the K-th Shortest Path","datePublished":"2024-11-01T09:33:47+00:00","dateModified":"2024-11-01T11:45:40+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/34934\/"},"wordCount":495,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Kotlin coding test"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/34934\/","url":"https:\/\/atmokpo.com\/w\/34934\/","name":"Kotlin Coding Test Course: Finding the K-th Shortest Path - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:33:47+00:00","dateModified":"2024-11-01T11:45:40+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/34934\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/34934\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/34934\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Kotlin Coding Test Course: Finding the K-th Shortest Path"}]},{"@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\/34934","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=34934"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34934\/revisions"}],"predecessor-version":[{"id":34935,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34934\/revisions\/34935"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=34934"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=34934"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=34934"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}