{"id":316,"date":"2025-06-13T14:36:26","date_gmt":"2025-06-13T09:06:26","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=316"},"modified":"2025-06-17T20:22:24","modified_gmt":"2025-06-17T14:52:24","slug":"shortest-path-in-an-undirected-graph","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/shortest-path-in-an-undirected-graph\/","title":{"rendered":"Shortest Path in an Undirected Graph with Unit Distance \u2013 Clear BFS Solution in Python"},"content":{"rendered":"\n<p>Find the Shortest Path in an Undirected Graph from a source to every other node when every edge costs 1. We build intuition for Breadth-First Search, walk through the code line by line, add a dry run, and finish with precise Big-O analysis.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/shortest-path-in-undirected-graph-having-unit-distance\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-3aa94aa0-92f4-4f5a-8237-f53cc892e187\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/shortest-path-in-an-undirected-graph\/#0-1-problem-statement\" style=\"\">1. Problem statement<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/shortest-path-in-an-undirected-graph\/#1-2-example\" style=\"\">2. Example<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/shortest-path-in-an-undirected-graph\/#2-3-intuition-amp-approach\" style=\"\">3. Intuition &amp; approach<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/shortest-path-in-an-undirected-graph\/#3-31%E2%80%82why-breadth-first-search-bfs\" style=\"\">3.1\u2002Why Breadth-First Search (BFS)?<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/shortest-path-in-an-undirected-graph\/#4-32%E2%80%82algorithm-steps\" style=\"\">3.2\u2002Algorithm steps<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/shortest-path-in-an-undirected-graph\/#5-4-python-code\" style=\"\">4. Python code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/shortest-path-in-an-undirected-graph\/#6-5-step-by-step-code-explanation\" style=\"\">5. Step-by-step code explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/shortest-path-in-an-undirected-graph\/#7-6-dry-run-on-the-earlier-example-graph\" style=\"\">6. Dry run on the earlier example graph<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/shortest-path-in-an-undirected-graph\/#8-7-complexity\" style=\"\">7. Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/shortest-path-in-an-undirected-graph\/#9-8-conclusion\" style=\"\">8. Conclusion<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-1-problem-statement\">1. Problem statement<\/h2>\n\n\n\n<p>You are given an <strong>undirected<\/strong> graph with <code>n<\/code> vertices (<code>0 \u2026 n-1<\/code>).<br>All edges have <strong>unit weight<\/strong> (cost = 1).<\/p>\n\n\n\n<p>For a given source vertex <code>src<\/code>, return an array <code>distance<\/code> where<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>distance[i]<\/code> = the <strong>fewest edges<\/strong> needed to reach vertex <code>i<\/code> from <code>src<\/code>,<\/li>\n\n\n\n<li>If a vertex is <strong>unreachable<\/strong>, its distance is <code>-1<\/code>.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-2-example\">2. Example<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"n = 6\nEdges:\n0-1, 0-2, 1-3, 2-3, 3-4\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">n = <\/span><span style=\"color: #B5CEA8\">6<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Edges:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">-<\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">-<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">-<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">-<\/span><span style=\"color: #B5CEA8\">4<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Vertex<\/th><th>Shortest path from 0<\/th><th>Distance<\/th><\/tr><\/thead><tbody><tr><td>0<\/td><td>0<\/td><td><strong>0<\/strong><\/td><\/tr><tr><td>1<\/td><td>0-1<\/td><td><strong>1<\/strong><\/td><\/tr><tr><td>2<\/td><td>0-2<\/td><td><strong>1<\/strong><\/td><\/tr><tr><td>3<\/td><td>0-1-3 or 0-2-3<\/td><td><strong>2<\/strong><\/td><\/tr><tr><td>4<\/td><td>0-1-3-4<\/td><td><strong>3<\/strong><\/td><\/tr><tr><td>5<\/td><td>\u2013<\/td><td><strong>-1<\/strong> (not connected)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><code>distance = [0, 1, 1, 2, 3, -1]<\/code><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-3-intuition-amp-approach\">3. Intuition &amp; approach<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-31%E2%80%82why-breadth-first-search-bfs\">3.1\u2002Why Breadth-First Search (BFS)?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Every edge costs the <strong>same<\/strong> (1).<\/li>\n\n\n\n<li>BFS explores the graph <strong>level by level<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Level 0 = source itself.<\/li>\n\n\n\n<li>Level 1 = all vertices one edge away.<\/li>\n\n\n\n<li>Level 2 = all vertices two edges away \u2026<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>The <strong>first time<\/strong> BFS reaches a vertex, it has already found the <strong>shortest possible path<\/strong> (fewest edges).<\/li>\n<\/ul>\n\n\n\n<p>So BFS gives us the answer in a single scan.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-32%E2%80%82algorithm-steps\">3.2\u2002Algorithm steps<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Setup a queue<\/strong> to process vertices in order of their distance.<\/li>\n\n\n\n<li><strong><code>distance[src] = 0<\/code><\/strong>; push <code>(src, 0)<\/code> into the queue.<\/li>\n\n\n\n<li><strong>Pop<\/strong> a vertex <code>(node, distSoFar)<\/code>\n<ul class=\"wp-block-list\">\n<li>For every neighbour <code>adjNode<\/code>\n<ul class=\"wp-block-list\">\n<li>If the neighbour hasn\u2019t been visited (<code>distance == -1<\/code>)\n<ul class=\"wp-block-list\">\n<li>Set <code>distance[adjNode] = distSoFar + 1<\/code><\/li>\n\n\n\n<li>Push <code>(adjNode, distSoFar + 1)<\/code> into the queue.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Repeat until the queue is empty.<\/li>\n\n\n\n<li>Return the <code>distance<\/code> array.<\/li>\n<\/ol>\n\n\n\n<p>Because each vertex enters the queue <strong>once<\/strong>, the algorithm runs in <strong>linear time<\/strong>.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><em>You may be interested in solving<\/em><strong><em> <a href=\"https:\/\/codeanddebug.in\/blog\/shortest-path-in-a-weighted-dag-topological-sort-relaxation-python\/\" target=\"_blank\" data-type=\"post\" data-id=\"319\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\">Shortest Path in a Weighted DAG<\/mark><\/a><\/em><\/strong>.<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-4-python-code\">4. Python code<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"from collections import deque\n\n\nclass Solution:\n    def shortestPath(self, adj, src):\n        n = len(adj)                                  # number of vertices\n        distance = [-1 for _ in range(n)]             # -1 = not reached yet\n        queue = deque()\n\n        queue.append([src, 0])                        # start from source\n        distance[src] = 0\n\n        while len(queue) != 0:\n            node, dis_trav = queue.popleft()          # current vertex + distance\n            for adjNode in adj[node]:                 # explore neighbours\n                if distance[adjNode] == -1:           # first time we see it\n                    distance[adjNode] = dis_trav + 1  # shortest path fixed\n                    queue.append([adjNode, dis_trav + 1])\n\n        return distance\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> collections <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> deque<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">shortestPath<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">adj<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">src<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(adj)                                  <\/span><span style=\"color: #6A9955\"># number of vertices<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        distance = [-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n)]             <\/span><span style=\"color: #6A9955\"># -1 = not reached yet<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        queue = deque()<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        queue.append([src, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">])                        <\/span><span style=\"color: #6A9955\"># start from source<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        distance[src] = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(queue) != <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            node, dis_trav = queue.popleft()          <\/span><span style=\"color: #6A9955\"># current vertex + distance<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> adjNode <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> adj[node]:                 <\/span><span style=\"color: #6A9955\"># explore neighbours<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> distance[adjNode] == -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:           <\/span><span style=\"color: #6A9955\"># first time we see it<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    distance[adjNode] = dis_trav + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">  <\/span><span style=\"color: #6A9955\"># shortest path fixed<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    queue.append([adjNode, dis_trav + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">])<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> distance<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-5-step-by-step-code-explanation\">5. Step-by-step code explanation<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Lines 6-8<\/strong> \u2013\n<ul class=\"wp-block-list\">\n<li><code>n<\/code> stores the vertex count.<\/li>\n\n\n\n<li><code>distance<\/code> array starts at <code>-1<\/code> for every vertex.<\/li>\n\n\n\n<li><code>queue<\/code> will maintain vertices to process in FIFO order.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Line 10<\/strong> \u2013 Push the source <code>(src, 0)<\/code>; distance to itself is 0.<\/li>\n\n\n\n<li><strong>Main <code>while<\/code> loop (Lines 12-17)<\/strong>\n<ul class=\"wp-block-list\">\n<li><code>popleft()<\/code> fetches the <em>closest unprocessed<\/em> vertex (<code>node<\/code>) and its current shortest distance (<code>dis_trav<\/code>).<\/li>\n\n\n\n<li>Loop over every neighbour <code>adjNode<\/code>:\n<ul class=\"wp-block-list\">\n<li><strong>Unvisited?<\/strong> (distance = -1)\n<ul class=\"wp-block-list\">\n<li>Set its distance to <code>dis_trav + 1<\/code>.<\/li>\n\n\n\n<li>Enqueue it with this new distance.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Each neighbour enters the queue <strong>once<\/strong>, ensuring O(V + E) time.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Line 17<\/strong> \u2013 When the queue empties, all reachable vertices have been assigned their minimum distances. The function returns the completed array.<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7-6-dry-run-on-the-earlier-example-graph\">6. Dry run on the earlier example graph<\/h2>\n\n\n\n<p>Queue state shown as <code>[vertex, dist]<\/code>.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Step<\/th><th>Queue (before pop)<\/th><th><code>distance<\/code> after processing<\/th><\/tr><\/thead><tbody><tr><td>Init<\/td><td><code>[[0,0]]<\/code><\/td><td><code>[0,-1,-1,-1,-1,-1]<\/code><\/td><\/tr><tr><td>Pop 0<\/td><td>neighbours 1,2 \u2192 enqueue <code>[1,1],[2,1]<\/code><\/td><td><code>[0,1,1,-1,-1,-1]<\/code><\/td><\/tr><tr><td>Pop 1<\/td><td>neighbour 3 (new) \u2192 enqueue <code>[3,2]<\/code><\/td><td><code>[0,1,1,2,-1,-1]<\/code><\/td><\/tr><tr><td>Pop 2<\/td><td>neighbour 3 already visited<\/td><td>unchanged<\/td><\/tr><tr><td>Pop 3<\/td><td>neighbour 4 \u2192 enqueue <code>[4,3]<\/code><\/td><td><code>[0,1,1,2,3,-1]<\/code><\/td><\/tr><tr><td>Pop 4<\/td><td>no new neighbour<\/td><td>unchanged<\/td><\/tr><tr><td>Queue empty<\/td><td>\u2013<\/td><td>Final distances<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Matches <code>[0, 1, 1, 2, 3, -1]<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8-7-complexity\">7. Complexity<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Measure<\/th><th>Value<\/th><th>Explanation<\/th><\/tr><\/thead><tbody><tr><td><strong>Time<\/strong><\/td><td><strong>O(V + E)<\/strong><\/td><td>Each vertex enqueued once; each undirected edge examined twice (once per direction)<\/td><\/tr><tr><td><strong>Space<\/strong><\/td><td><strong>O(V)<\/strong><\/td><td><code>distance<\/code> array + queue (worst-case all vertices inside)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><code>V = n<\/code>, <code>E = number of edges<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"9-8-conclusion\">8. Conclusion<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Breadth-First Search<\/strong> is the go-to tool for shortest paths when all edges cost the same.<\/li>\n\n\n\n<li>A single queue and a <code>distance<\/code> array are enough, no fancy data structures.<\/li>\n\n\n\n<li>Because we mark a vertex the first time we see it, its distance is already minimal.<\/li>\n\n\n\n<li>The solution is linear, easy to code, and scales to very large sparse graphs.<\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/www.codeanddebug.in\/course\/zero-to-hero-python-dsa\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Find the Shortest Path in an Undirected Graph from a source to every other node when every edge costs 1. We build intuition for Breadth-First Search, walk through the code line by line, add a dry run, and finish with precise Big-O analysis. Here&#8217;s the [Problem Link] to begin with. 1. Problem statement You are<\/p>\n","protected":false},"author":1,"featured_media":317,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[21,17,19,23],"class_list":{"0":"post-316","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-bfs","10":"tag-graph","11":"tag-medium","12":"tag-shortest-path"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/shortest-path-in-undirected-graph-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/316","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=316"}],"version-history":[{"count":3,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/316\/revisions"}],"predecessor-version":[{"id":325,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/316\/revisions\/325"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/317"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=316"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=316"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=316"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}