{"id":34614,"date":"2024-11-01T09:30:06","date_gmt":"2024-11-01T09:30:06","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=34614"},"modified":"2024-11-01T11:40:29","modified_gmt":"2024-11-01T11:40:29","slug":"javascript-coding-test-course-finding-the-k-th-shortest-path","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/34614\/","title":{"rendered":"JavaScript Coding Test Course, Finding the K-th Shortest Path"},"content":{"rendered":"<p><body><\/p>\n<p>In this course, we will address an algorithm problem that finds the Kth shortest path using JavaScript. This problem requires a solid understanding of graph theory and pathfinding algorithms and focuses on writing efficient code.<\/p>\n<h2>Problem Description<\/h2>\n<p>Essentially, you need to find the total length of the Kth shortest path among all possible paths from one vertex to another in the given graph.<\/p>\n<h3>Problem Input<\/h3>\n<ul>\n<li><strong>N<\/strong>: The number of vertices (1 \u2264 N \u2264 100)<\/li>\n<li><strong>M<\/strong>: The number of edges (1 \u2264 M \u2264 1000)<\/li>\n<li><strong>K<\/strong>: The rank of the desired path (1 \u2264 K \u2264 10)<\/li>\n<li>Afterward, the edge information will be provided over <strong>M<\/strong> lines.<br \/>\n        Each edge information is composed of <strong>u, v, w<\/strong>, which means that the weight from vertex <strong>u<\/strong> to vertex <strong>v<\/strong> is <strong>w<\/strong>.<\/li>\n<\/ul>\n<h3>Output<\/h3>\n<p>Print the total length of the Kth shortest path. If the Kth shortest path does not exist, you should print -1.<\/p>\n<h2>Example<\/h2>\n<div class=\"example\">\n<h3>Input Example<\/h3>\n<pre>\n    4 5 2\n    1 2 4\n    1 3 2\n    3 2 5\n    2 4 1\n    3 4 3\n    <\/pre>\n<h3>Output Example<\/h3>\n<pre>\n    5\n    <\/pre>\n<\/div>\n<h2>Problem-Solving Approach<\/h2>\n<p>To find the Kth shortest path, one of the methods is to modify Dijkstra&#8217;s algorithm. The Dijkstra algorithm is primarily used to find the shortest path, but to find the Kth shortest path, it needs to allow for multiple explorations of paths.<\/p>\n<h3>Step-by-Step Solution Process<\/h3>\n<h4>1. Graph Representation<\/h4>\n<p>The graph is represented in the form of an adjacency list, with each node storing information about its connected nodes and the weights of those paths. This allows Dijkstra&#8217;s algorithm to be applied efficiently.<\/p>\n<h4>2. Using a Priority Queue<\/h4>\n<p>Using JavaScript&#8217;s <code>PriorityQueue<\/code> to prioritize the exploration of the shortest path. It holds the information of each path, allowing for exploration starting from the minimum cost, just like Dijkstra&#8217;s algorithm.<\/p>\n<h4>3. Kth Path Exploration<\/h4>\n<p>While exploring paths, maintain a count to find the Kth shortest path. Store the lengths of paths in an array, returning the length when the Kth path is reached; otherwise, continue exploring.<\/p>\n<h4>4. Result Output<\/h4>\n<p>After exploring all paths, output -1 if the Kth path does not exist.<\/p>\n<h2>Implementation Code<\/h2>\n<p>The code below is a JavaScript version that finds the Kth shortest path based on the explanation above.<\/p>\n<pre><code>\nclass MinHeap {\n    constructor() {\n        this.heap = [];\n    }\n\n    insert(node) {\n        this.heap.push(node);\n        this.bubbleUp();\n    }\n\n    bubbleUp() {\n        let index = this.heap.length - 1;\n        const element = this.heap[index];\n\n        while (index > 0) {\n            let parentIndex = Math.floor((index - 1) \/ 2);\n            let parent = this.heap[parentIndex];\n\n            if (element[1] >= parent[1]) break;\n\n            this.heap[index] = parent;\n            index = parentIndex;\n        }\n        this.heap[index] = element;\n    }\n\n    extractMin() {\n        const min = this.heap[0];\n        const end = this.heap.pop();\n        if (this.heap.length > 0) {\n            this.heap[0] = end;\n            this.sinkDown();\n        }\n        return min;\n    }\n\n    sinkDown() {\n        let index = 0;\n        const length = this.heap.length;\n        const element = this.heap[0];\n\n        while (true) {\n            let leftChildIndex = 2 * index + 1;\n            let rightChildIndex = 2 * index + 2;\n            let leftChild, rightChild;\n            let swap = null;\n\n            if (leftChildIndex < length) {\n                leftChild = this.heap[leftChildIndex];\n                if (leftChild[1] < element[1]) {\n                    swap = leftChildIndex;\n                }\n            }\n\n            if (rightChildIndex < length) {\n                rightChild = this.heap[rightChildIndex];\n                if ((swap === null &#038;&#038; rightChild[1] < element[1]) || \n                    (swap !== null &#038;&#038; rightChild[1] < leftChild[1])) {\n                    swap = rightChildIndex;\n                }\n            }\n\n            if (swap === null) break;\n\n            this.heap[index] = this.heap[swap];\n            index = swap;\n        }\n        this.heap[index] = element;\n    }\n}\n\nfunction kthShortestPath(n, edges, k) {\n    const graph = Array.from({ length: n + 1 }, () => []);\n    edges.forEach(([u, v, w]) => {\n        graph[u].push([v, w]);\n    });\n\n    const minHeap = new MinHeap();\n    const paths = Array.from({ length: n + 1 }, () => []);\n\n    minHeap.insert([1, 0]);\n    paths[1].push(0);\n\n    while (minHeap.heap.length > 0) {\n        const [node, distance] = minHeap.extractMin();\n\n        if (paths[node].length === k) continue;\n\n        for (const [neighbor, weight] of graph[node]) {\n            const newDistance = distance + weight;\n\n            if (paths[neighbor].length < k) {\n                paths[neighbor].push(newDistance);\n                paths[neighbor].sort((a, b) => a - b);\n                minHeap.insert([neighbor, newDistance]);\n            } else if (newDistance < paths[neighbor][paths[neighbor].length - 1]) {\n                paths[neighbor][paths[neighbor].length - 1] = newDistance;\n                paths[neighbor].sort((a, b) => a - b);\n                minHeap.insert([neighbor, newDistance]);\n            }\n        }\n    }\n\n    return paths[n][k - 1] || -1;\n}\n\n\/\/ Example usage\nconst n = 4;\nconst edges = [\n    [1, 2, 4],\n    [1, 3, 2],\n    [3, 2, 5],\n    [2, 4, 1],\n    [3, 4, 3],\n];\nconst k = 2;\n\nconsole.log(kthShortestPath(n, edges, k)); \/\/ Output: 5\n<\/code><\/pre>\n<h2>Conclusion<\/h2>\n<p>In this course, we discussed algorithms for finding the Kth shortest path. We learned techniques to solve problems based on shortest path algorithms. With this foundation, we can develop the ability to solve more complex graph problems.<\/p>\n<div class=\"note\">\n<strong>Tip:<\/strong> In the process of solving algorithm problems, it&#8217;s important to explore various approaches and think about ways to improve the efficiency of your code. Try solving various graph problems to apply theory to practice.\n<\/div>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this course, we will address an algorithm problem that finds the Kth shortest path using JavaScript. This problem requires a solid understanding of graph theory and pathfinding algorithms and focuses on writing efficient code. Problem Description Essentially, you need to find the total length of the Kth shortest path among all possible paths from &hellip; <a href=\"https:\/\/atmokpo.com\/w\/34614\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;JavaScript 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":[141],"tags":[],"class_list":["post-34614","post","type-post","status-publish","format-standard","hentry","category-javascript-coding-test"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>JavaScript 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\/34614\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"JavaScript Coding Test Course, Finding the K-th Shortest Path - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"In this course, we will address an algorithm problem that finds the Kth shortest path using JavaScript. This problem requires a solid understanding of graph theory and pathfinding algorithms and focuses on writing efficient code. Problem Description Essentially, you need to find the total length of the Kth shortest path among all possible paths from &hellip; \ub354 \ubcf4\uae30 &quot;JavaScript Coding Test Course, Finding the K-th Shortest Path&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/34614\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:30:06+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:40:29+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=\"3\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/34614\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34614\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"JavaScript Coding Test Course, Finding the K-th Shortest Path\",\"datePublished\":\"2024-11-01T09:30:06+00:00\",\"dateModified\":\"2024-11-01T11:40:29+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34614\/\"},\"wordCount\":417,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Javascript Coding Test\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/34614\/\",\"url\":\"https:\/\/atmokpo.com\/w\/34614\/\",\"name\":\"JavaScript 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:30:06+00:00\",\"dateModified\":\"2024-11-01T11:40:29+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34614\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/34614\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/34614\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"JavaScript 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":"JavaScript 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\/34614\/","og_locale":"ko_KR","og_type":"article","og_title":"JavaScript Coding Test Course, Finding the K-th Shortest Path - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"In this course, we will address an algorithm problem that finds the Kth shortest path using JavaScript. This problem requires a solid understanding of graph theory and pathfinding algorithms and focuses on writing efficient code. Problem Description Essentially, you need to find the total length of the Kth shortest path among all possible paths from &hellip; \ub354 \ubcf4\uae30 \"JavaScript Coding Test Course, Finding the K-th Shortest Path\"","og_url":"https:\/\/atmokpo.com\/w\/34614\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:30:06+00:00","article_modified_time":"2024-11-01T11:40:29+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":"3\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/34614\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/34614\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"JavaScript Coding Test Course, Finding the K-th Shortest Path","datePublished":"2024-11-01T09:30:06+00:00","dateModified":"2024-11-01T11:40:29+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/34614\/"},"wordCount":417,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Javascript Coding Test"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/34614\/","url":"https:\/\/atmokpo.com\/w\/34614\/","name":"JavaScript 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:30:06+00:00","dateModified":"2024-11-01T11:40:29+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/34614\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/34614\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/34614\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"JavaScript 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\/34614","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=34614"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34614\/revisions"}],"predecessor-version":[{"id":34615,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34614\/revisions\/34615"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=34614"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=34614"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=34614"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}