{"id":132,"date":"2025-05-22T16:30:59","date_gmt":"2025-05-22T11:00:59","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=132"},"modified":"2025-05-22T16:31:00","modified_gmt":"2025-05-22T11:01:00","slug":"breadth-first-search-in-graph","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/breadth-first-search-in-graph\/","title":{"rendered":"BFS Traversal in Graph | Explained using Code"},"content":{"rendered":"\n<p>Learn how to perform BFS Traversal in Graph represented by an adjacency list. This hands guide uses Python\u2019s <code>collections.deque<\/code>, walks through the code line by line, and shows a simple dry run, perfect for coding interviews and GFG practice!<\/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-09001058-88c1-4988-aa9a-3d5e17939e2e\" 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\">Content:<\/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\/breadth-first-search-in-graph\/#0-what-the-problem-asks\" style=\"\">What the Problem Asks<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/breadth-first-search-in-graph\/#1-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/breadth-first-search-in-graph\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/breadth-first-search-in-graph\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/breadth-first-search-in-graph\/#4-dry-run-example\" style=\"\">Dry Run Example<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/breadth-first-search-in-graph\/#5-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/breadth-first-search-in-graph\/#6-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-what-the-problem-asks\">What the Problem Asks<\/h2>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>BFS Traversal of Graph<\/strong><br>Given a graph in the form of an adjacency list, perform a <strong>Breadth-First Search (BFS)<\/strong> starting from vertex <strong>0 <\/strong>and return the order in which nodes are visited.<\/p>\n<\/blockquote>\n\n\n\n<p><strong>Input:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>adj<\/code>: A list of <code>n<\/code> lists, where <code>adj[u]<\/code> contains all neighbors of node <code>u<\/code>.<\/li>\n<\/ul>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A list of vertices in the order they\u2019re visited by BFS, beginning at node <code>0<\/code>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-intuition-amp-approach\">Intuition &amp; Approach<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>BFS<\/strong> explores a graph <strong>level by level<\/strong>.<\/li>\n\n\n\n<li>You start at the source (<code>0<\/code>), then visit <strong>all neighbors<\/strong> of <code>0<\/code>, then all unvisited neighbors of those, and so on.<\/li>\n\n\n\n<li>A <strong>queue<\/strong> ensures you visit in the correct order: first-in, first-out.<\/li>\n\n\n\n<li>A <strong>visited<\/strong> array prevents revisiting nodes (and getting stuck in cycles).<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-code-implementation\">Code Implementation<\/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\nclass Solution:\n    # Function that does BFS from 'start' and returns the visit order.\n    def bfs_algo(self, n, adj, start):\n        ans = []                  # stores the BFS order\n        visited = [0] * n         # 0 = unvisited, 1 = visited\n        queue = deque([start])    # our queue, seeded with the start node\n        visited[start] = 1\n\n        while queue:\n            u = queue.popleft()   # take the next node\n            ans.append(u)         # record it\n\n            # enqueue all unvisited neighbors\n            for v in adj[u]:\n                if visited[v] == 0:\n                    visited[v] = 1\n                    queue.append(v)\n\n        return ans\n\n    def bfs(self, adj):\n        n = len(adj)\n        return self.bfs_algo(n, adj, 0)\" 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 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: #6A9955\"># Function that does BFS from &#39;start&#39; and returns the visit order.<\/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\">bfs_algo<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">n<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">adj<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">start<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        ans = []                  <\/span><span style=\"color: #6A9955\"># stores the BFS order<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        visited = [<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">] * n         <\/span><span style=\"color: #6A9955\"># 0 = unvisited, 1 = visited<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        queue = deque([start])    <\/span><span style=\"color: #6A9955\"># our queue, seeded with the start node<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        visited[start] = <\/span><span style=\"color: #B5CEA8\">1<\/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\"> queue:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            u = queue.popleft()   <\/span><span style=\"color: #6A9955\"># take the next node<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            ans.append(u)         <\/span><span style=\"color: #6A9955\"># record it<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># enqueue all unvisited neighbors<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> v <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> adj[u]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> visited[v] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    visited[v] = <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    queue.append(v)<\/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\"> ans<\/span><\/span>\n<span class=\"line\"><\/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\">bfs<\/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>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(adj)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.bfs_algo(n, adj, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-code-explanation\">Code Explanation<\/h2>\n\n\n\n<p><strong>Initialization<\/strong><\/p>\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=\"ans = []\nvisited = [0] * n\nqueue = deque([start])\nvisited[start] = 1\" 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\">ans = []<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">visited = [<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">] * n<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">queue = deque([start])<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">visited[start] = <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>ans<\/code><\/strong> collects the order of visited nodes.<\/li>\n\n\n\n<li><strong><code>visited<\/code><\/strong> tracks which nodes we\u2019ve already enqueued.<\/li>\n\n\n\n<li><strong><code>queue<\/code><\/strong> begins with the <code>start<\/code> node (<code>0<\/code>), and we mark it visited.<\/li>\n<\/ul>\n\n\n\n<p><strong>BFS Loop<\/strong><\/p>\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=\"while queue:\n    u = queue.popleft()\n    ans.append(u)\n    for v in adj[u]:\n        if not visited[v]:\n            visited[v] = 1\n            queue.append(v)\" 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\">while<\/span><span style=\"color: #D4D4D4\"> queue:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    u = queue.popleft()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    ans.append(u)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> v <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> adj[u]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">not<\/span><span style=\"color: #D4D4D4\"> visited[v]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            visited[v] = <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            queue.append(v)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>popleft()<\/code><\/strong> gives the next node in FIFO order.<\/li>\n\n\n\n<li>We <strong>append<\/strong> it to our answer list.<\/li>\n\n\n\n<li>Then for <strong>each neighbor <code>v<\/code><\/strong>, if it\u2019s unvisited, we mark it visited and <strong>enqueue<\/strong> it.<\/li>\n<\/ul>\n\n\n\n<p><strong>Return<\/strong><\/p>\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=\"return ans\" 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\">return<\/span><span style=\"color: #D4D4D4\"> ans<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Once the queue is empty, we\u2019ve visited all reachable nodes in BFS order.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-dry-run-example\">Dry Run Example<\/h2>\n\n\n\n<p>Consider this graph (<code>n = 5<\/code>):<\/p>\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=\"Adjacency List:\n0: [1, 2]\n1: [0, 3]\n2: [0, 4]\n3: [1]\n4: [2]\" 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\">Adjacency List:<\/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\">2<\/span><span style=\"color: #D4D4D4\">]<\/span><\/span>\n<span class=\"line\"><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\">3<\/span><span style=\"color: #D4D4D4\">]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">: [<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">: [<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">: [<\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">]<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>Starting at node <code>0<\/code>:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Queue<\/strong> = <code>[0]<\/code>, <strong>ans<\/strong> = <code>[]<\/code>, <strong>visited<\/strong> = <code>[1,0,0,0,0]<\/code><\/li>\n\n\n\n<li>Pop <code>0<\/code> \u2192 <code>ans = [0]<\/code>. Enqueue its neighbors <code>1<\/code>, <code>2<\/code>:\n<ul class=\"wp-block-list\">\n<li><strong>Queue<\/strong> = <code>[1,2]<\/code>, <strong>visited<\/strong> = <code>[1,1,1,0,0]<\/code><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Pop <code>1<\/code> \u2192 <code>ans = [0,1]<\/code>. Enqueue unvisited neighbor <code>3<\/code>:\n<ul class=\"wp-block-list\">\n<li><strong>Queue<\/strong> = <code>[2,3]<\/code>, <strong>visited<\/strong> = <code>[1,1,1,1,0]<\/code><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Pop <code>2<\/code> \u2192 <code>ans = [0,1,2]<\/code>. Enqueue unvisited neighbor <code>4<\/code>:\n<ul class=\"wp-block-list\">\n<li><strong>Queue<\/strong> = <code>[3,4]<\/code>, <strong>visited<\/strong> = <code>[1,1,1,1,1]<\/code><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Pop <code>3<\/code> \u2192 <code>ans = [0,1,2,3]<\/code> (no new neighbors)<\/li>\n\n\n\n<li>Pop <code>4<\/code> \u2192 <code>ans = [0,1,2,3,4]<\/code> (no new neighbors)<\/li>\n\n\n\n<li><strong>Queue<\/strong> is empty \u2192 done.<\/li>\n<\/ol>\n\n\n\n<p>Final BFS order: <strong>[0, 1, 2, 3, 4]<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-time-amp-space-complexity\">Time &amp; Space Complexity<\/h2>\n\n\n\n<p><strong>Time Complexity:<\/strong> O(V + 2E)<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We visit each vertex once and examine each edge once.<\/li>\n<\/ul>\n\n\n\n<p><strong>Space Complexity:<\/strong> O(3V)<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <strong><code>visited<\/code> <\/strong>array, the <strong><code>ans<\/code> <\/strong>list, and the <strong>queue<\/strong> all use up to O(3V) space.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-conclusion\">Conclusion<\/h2>\n\n\n\n<p>With just a few lines and Python\u2019s <strong><code>deque<\/code><\/strong>, you can implement BFS and get the level-by-level order of any graph (or tree). BFS is essential not only for graph traversal but also for shortest-path problems, web crawling, and more. Mastering this pattern will boost your confidence for both <strong>GeeksforGeeks<\/strong> practice and coding interviews. Happy traversing!<\/p>\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:\/\/codeanddebug.in\/course\/master-dsa-with-leetcode\" target=\"_blank\" rel=\"noreferrer noopener\">Join our free 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\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to perform BFS Traversal in Graph represented by an adjacency list. This hands guide uses Python\u2019s collections.deque, walks through the code line by line, and shows a simple dry run, perfect for coding interviews and GFG practice! What the Problem Asks BFS Traversal of GraphGiven a graph in the form of an adjacency<\/p>\n","protected":false},"author":1,"featured_media":134,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[17],"class_list":{"0":"post-132","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-graph"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/05\/breadth-first-search-in-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\/132","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=132"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/132\/revisions"}],"predecessor-version":[{"id":136,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/132\/revisions\/136"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/134"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=132"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=132"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=132"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}