{"id":34308,"date":"2024-11-01T09:26:40","date_gmt":"2024-11-01T09:26:40","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=34308"},"modified":"2024-11-01T10:57:46","modified_gmt":"2024-11-01T10:57:46","slug":"c-coding-test-course-finding-the-shortest-path-2","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/34308\/","title":{"rendered":"C++ Coding Test Course, Finding the Shortest Path"},"content":{"rendered":"<p><body><\/p>\n<h2>1. Problem Definition<\/h2>\n<p>The shortest path problem is the problem of finding the minimum distance between two vertices in a given graph. The graph consists of nodes (vertices) and edges connecting them, with each edge expressed as a distance or weight.<\/p>\n<p>For example, let&#8217;s assume there is a graph like the one below. Here, A, B, C, and D are nodes, and the edges have the following weights:<\/p>\n<pre>\n    A --1-- B\n    |      \/|\n    4     2 |\n    |  \/      |\n    C --3-- D\n    <\/pre>\n<p>The task is to find the shortest path between two nodes A and D.<\/p>\n<h2>2. Algorithm Selection<\/h2>\n<p>The algorithms commonly used to solve the shortest path problem are Dijkstra&#8217;s algorithm and the Bellman-Ford algorithm.<\/p>\n<p>In this problem, we will use Dijkstra&#8217;s algorithm, which is suitable for finding the shortest path in graphs with non-negative weights.<\/p>\n<h3>2.1 Explanation of Dijkstra&#8217;s Algorithm<\/h3>\n<p>Dijkstra&#8217;s algorithm works in the following steps:<\/p>\n<ol>\n<li>Set the starting node and initialize the shortest distance to that node as 0.<\/li>\n<li>Initialize the shortest distances for all other nodes to infinity.<\/li>\n<li>Select the unvisited node with the lowest shortest distance value.<\/li>\n<li>Set this node as the current node and update the shortest distance values of all adjacent nodes reachable through this node.<\/li>\n<li>Repeat steps 3-4 until all nodes are visited.<\/li>\n<\/ol>\n<h2>3. C++ Implementation<\/h2>\n<p>Now let&#8217;s implement Dijkstra&#8217;s algorithm in C++. Below is the code for finding the shortest path in the graph described above:<\/p>\n<pre>\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;queue&gt;\n#include &lt;limits&gt; \/\/ for numeric_limits\nusing namespace std;\n\n\/\/ Graph structure definition\nstruct Edge {\n    int destination;\n    int weight;\n};\n\n\/\/ Dijkstra's algorithm implementation\nvector<int> dijkstra(int start, const vector<vector<Edge>&gt;&amp; graph) {\n    int n = graph.size();\n    vector<int> distance(n, numeric_limits<int>::max());\n    distance[start] = 0;\n    \n    priority_queue<pair<int, int=\"\">, vector<pair<int, int=\"\">&gt;, greater<pair<int, int=\"\">&gt;&gt; minHeap;\n    minHeap.push({0, start});\n\n    while (!minHeap.empty()) {\n        int currentDistance = minHeap.top().first;\n        int currentNode = minHeap.top().second;\n        minHeap.pop();\n\n        \/\/ Ignore if the current node's distance value is greater\n        if (currentDistance &gt; distance[currentNode]) continue;\n\n        \/\/ Explore adjacent nodes\n        for (const Edge&amp; edge : graph[currentNode]) {\n            int newDistance = currentDistance + edge.weight;\n            if (newDistance &lt; distance[edge.destination]) {\n                distance[edge.destination] = newDistance;\n                minHeap.push({newDistance, edge.destination});\n            }\n        }\n    }\n\n    return distance;\n}\n\nint main() {\n    \/\/ Initialize the graph\n    int n = 4; \/\/ Number of nodes\n    vector<vector<Edge>&gt; graph(n);\n    \n    \/\/ Add edges (0-based index)\n    graph[0].push_back({1, 1});\n    graph[0].push_back({2, 4});\n    graph[1].push_back({2, 2});\n    graph[1].push_back({3, 1});\n    graph[2].push_back({3, 3});\n    \n    int startNode = 0; \/\/ A\n    vector<int> shortestPaths = dijkstra(startNode, graph);\n\n    \/\/ Print results\n    cout &lt;&lt; \"Shortest Path:\" &lt;&lt; endl;\n    for (int i = 0; i &lt; n; i++) {\n        cout &lt;&lt; \"Shortest path from A to \" &lt;&lt; char('A' + i) &lt;&lt; \": \";\n        if (shortestPaths[i] == numeric_limits<int>::max()) {\n            cout &lt;&lt; \"Unreachable\" &lt;&lt; endl;\n        } else {\n            cout &lt;&lt; shortestPaths[i] &lt;&lt; endl;\n        }\n    }\n\n    return 0;\n}\n    <\/int><\/int><\/vector<Edge><\/pair<int,><\/pair<int,><\/pair<int,><\/int><\/int><\/vector<Edge><\/int><\/pre>\n<h2>4. Code Explanation<\/h2>\n<h3>4.1 Graph Structure Setup<\/h3>\n<p>First, we define the edge structure to create a graph that includes information for each node and weight. We use <code>vector&lt;vector&lt;Edge&gt;&gt;<\/code> to represent the graph.<\/p>\n<h3>4.2 Implementation of Dijkstra<\/h3>\n<p>We wrote the function <code>dijkstra<\/code> for Dijkstra&#8217;s algorithm. It calculates the shortest distance from the starting node to each node and stores it in the <code>distance<\/code> vector. We use a <code>priority_queue<\/code> to efficiently manage the current shortest paths.<\/p>\n<h3>4.3 Main Function<\/h3>\n<p>The <code>main<\/code> function initializes the graph, calls the Dijkstra function to find the shortest path, and then prints the results.<\/p>\n<h2>5. Complexity Analysis<\/h2>\n<p>The time complexity of Dijkstra&#8217;s algorithm depends on the data structure used. Generally, when using a heap, it is represented as <code>O(E log V)<\/code>, where <code>E<\/code> is the number of edges and <code>V<\/code> is the number of nodes.<\/p>\n<h2>6. References<\/h2>\n<ul>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/Dijkstra's_algorithm\" target=\"_blank\" rel=\"noopener\">Dijkstra&#8217;s Algorithm &#8211; Wikipedia<\/a><\/li>\n<li><a href=\"https:\/\/www.geeksforgeeks.org\/dijkstras-shortest-path-algorithm-using-priority_queue-in-c\/\" target=\"_blank\" rel=\"noopener\">GeeksforGeeks &#8211; Dijkstra&#8217;s Algorithm Implementation<\/a><\/li>\n<\/ul>\n<div class=\"note\">\n<strong>Note:<\/strong> This code works for the sample graph and needs to be modified for actual problem scenarios. Variants of Dijkstra&#8217;s algorithm or other approaches can be considered to tackle similar types of problems.\n    <\/div>\n<h2>7. Conclusion<\/h2>\n<p>In this article, we learned how to find the shortest path in a given graph using Dijkstra&#8217;s algorithm implemented in C++. By understanding the basic concepts of the algorithm and its C++ implementation, we could deepen our understanding through examples. It is important to apply such algorithms to problem-solving during actual coding tests. Continuously solving various problems will help you gain experience.<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. Problem Definition The shortest path problem is the problem of finding the minimum distance between two vertices in a given graph. The graph consists of nodes (vertices) and edges connecting them, with each edge expressed as a distance or weight. For example, let&#8217;s assume there is a graph like the one below. Here, A, &hellip; <a href=\"https:\/\/atmokpo.com\/w\/34308\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;C++ Coding Test Course, Finding the 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":[111],"tags":[],"class_list":["post-34308","post","type-post","status-publish","format-standard","hentry","category-c-coding-test-tutorials-2"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>C++ Coding Test Course, Finding the 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\/34308\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"C++ Coding Test Course, Finding the Shortest Path - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"1. Problem Definition The shortest path problem is the problem of finding the minimum distance between two vertices in a given graph. The graph consists of nodes (vertices) and edges connecting them, with each edge expressed as a distance or weight. For example, let&#8217;s assume there is a graph like the one below. Here, A, &hellip; \ub354 \ubcf4\uae30 &quot;C++ Coding Test Course, Finding the Shortest Path&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/34308\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:26:40+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T10:57:46+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=\"1\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/34308\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34308\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"C++ Coding Test Course, Finding the Shortest Path\",\"datePublished\":\"2024-11-01T09:26:40+00:00\",\"dateModified\":\"2024-11-01T10:57:46+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34308\/\"},\"wordCount\":467,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"C++ Coding Test Tutorials\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/34308\/\",\"url\":\"https:\/\/atmokpo.com\/w\/34308\/\",\"name\":\"C++ Coding Test Course, Finding the Shortest Path - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:26:40+00:00\",\"dateModified\":\"2024-11-01T10:57:46+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34308\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/34308\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/34308\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"C++ Coding Test Course, Finding the 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":"C++ Coding Test Course, Finding the 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\/34308\/","og_locale":"ko_KR","og_type":"article","og_title":"C++ Coding Test Course, Finding the Shortest Path - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"1. Problem Definition The shortest path problem is the problem of finding the minimum distance between two vertices in a given graph. The graph consists of nodes (vertices) and edges connecting them, with each edge expressed as a distance or weight. For example, let&#8217;s assume there is a graph like the one below. Here, A, &hellip; \ub354 \ubcf4\uae30 \"C++ Coding Test Course, Finding the Shortest Path\"","og_url":"https:\/\/atmokpo.com\/w\/34308\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:26:40+00:00","article_modified_time":"2024-11-01T10:57:46+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":"1\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/34308\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/34308\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"C++ Coding Test Course, Finding the Shortest Path","datePublished":"2024-11-01T09:26:40+00:00","dateModified":"2024-11-01T10:57:46+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/34308\/"},"wordCount":467,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["C++ Coding Test Tutorials"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/34308\/","url":"https:\/\/atmokpo.com\/w\/34308\/","name":"C++ Coding Test Course, Finding the Shortest Path - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:26:40+00:00","dateModified":"2024-11-01T10:57:46+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/34308\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/34308\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/34308\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"C++ Coding Test Course, Finding the 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\/34308","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=34308"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34308\/revisions"}],"predecessor-version":[{"id":34309,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34308\/revisions\/34309"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=34308"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=34308"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=34308"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}