{"id":525,"date":"2024-10-10T13:37:58","date_gmt":"2024-10-10T08:07:58","guid":{"rendered":"https:\/\/codexplained.in\/?p=525"},"modified":"2025-11-24T16:00:08","modified_gmt":"2025-11-24T10:30:08","slug":"implement-breadth-first-search-bfs","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=525","title":{"rendered":"Implementation of Breadth First Search (BFS)"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">What is Breadth First Search (BFS)?<\/h3>\n\n\n\n<p>BFS is a traversal algorithm for graph or tree data structures. It explores nodes level by level, starting from a specified node (often called the source) and moving outward. BFS is commonly used to find the shortest path in an unweighted graph.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Key Components of BFS<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Queue<\/strong>: BFS uses a queue to keep track of nodes that need to be explored next. This ensures that we explore nodes in the order they are discovered.<\/li>\n\n\n\n<li><strong>Visited Array<\/strong>: We maintain an array to keep track of visited nodes to prevent processing the same node multiple times.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Code<\/h2>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n#define MAX_NODES 100\n\n\/\/ Structure to represent a queue\ntypedef struct {\n    int items&#x5B;MAX_NODES];\n    int front, rear;\n} Queue;\n\n\/\/ Function to create a queue\nQueue* createQueue() {\n    Queue* q = (Queue*)malloc(sizeof(Queue));\n    q-&gt;front = -1;\n    q-&gt;rear = -1;\n    return q;\n}\n\n\/\/ Function to check if the queue is empty\nint isEmpty(Queue* q) {\n    return q-&gt;front == -1;\n}\n\n\/\/ Function to add an element to the queue\nvoid enqueue(Queue* q, int value) {\n    if (q-&gt;rear == MAX_NODES - 1) {\n        printf(&quot;Queue is full\\n&quot;);\n    } else {\n        if (q-&gt;front == -1) {\n            q-&gt;front = 0;\n        }\n        q-&gt;rear++;\n        q-&gt;items&#x5B;q-&gt;rear] = value;\n    }\n}\n\n\/\/ Function to remove an element from the queue\nint dequeue(Queue* q) {\n    if (isEmpty(q)) {\n        printf(&quot;Queue is empty\\n&quot;);\n        return -1;\n    } else {\n        int item = q-&gt;items&#x5B;q-&gt;front];\n        if (q-&gt;front &gt;= q-&gt;rear) {\n            q-&gt;front = q-&gt;rear = -1; \/\/ Reset queue\n        } else {\n            q-&gt;front++;\n        }\n        return item;\n    }\n}\n\n\/\/ Function to perform BFS and search for a specific node\nint bfs(int graph&#x5B;MAX_NODES]&#x5B;MAX_NODES], int start, int target, int num_nodes) {\n    int visited&#x5B;MAX_NODES] = {0}; \/\/ Array to track visited nodes\n    Queue* q = createQueue();     \/\/ Create the queue\n\n    \/\/ Start from the initial node\n    visited&#x5B;start] = 1;           \/\/ Mark it as visited\n    enqueue(q, start);            \/\/ Enqueue the starting node\n\n    printf(&quot;BFS Traversal: &quot;);\n\n    while (!isEmpty(q)) {\n        int current = dequeue(q);  \/\/ Dequeue a vertex\n        printf(&quot;%d &quot;, current);     \/\/ Print it\n\n        \/\/ Check if we found the target node\n        if (current == target) {\n            printf(&quot;\\nNode %d found!\\n&quot;, target);\n            return 1; \/\/ Node found\n        }\n\n        \/\/ Explore all adjacent nodes\n        for (int i = 0; i &lt; num_nodes; i++) {\n            if (graph&#x5B;current]&#x5B;i] == 1 &amp;&amp; !visited&#x5B;i]) { \/\/ If there&#039;s an edge and not visited\n                visited&#x5B;i] = 1;        \/\/ Mark it as visited\n                enqueue(q, i);         \/\/ Enqueue the adjacent node\n            }\n        }\n    }\n    \n    printf(&quot;\\nNode %d not found.\\n&quot;, target);\n    return 0; \/\/ Node not found\n}\n\n\/\/ Main function\nint main() {\n    \/\/ Example graph represented as an adjacency matrix\n    int graph&#x5B;MAX_NODES]&#x5B;MAX_NODES] = {0};\n    int num_nodes = 7;\n\n    \/\/ Adding edges\n    graph&#x5B;0]&#x5B;1] = graph&#x5B;1]&#x5B;0] = 1; \/\/ Edge between 0 and 1\n    graph&#x5B;0]&#x5B;2] = graph&#x5B;2]&#x5B;0] = 1; \/\/ Edge between 0 and 2\n    graph&#x5B;1]&#x5B;3] = graph&#x5B;3]&#x5B;1] = 1; \/\/ Edge between 1 and 3\n    graph&#x5B;1]&#x5B;4] = graph&#x5B;4]&#x5B;1] = 1; \/\/ Edge between 1 and 4\n    graph&#x5B;2]&#x5B;5] = graph&#x5B;5]&#x5B;2] = 1; \/\/ Edge between 2 and 5\n    graph&#x5B;2]&#x5B;6] = graph&#x5B;6]&#x5B;2] = 1; \/\/ Edge between 2 and 6\n\n    int target;\n    printf(&quot;Enter the node to search for: &quot;);\n    scanf(&quot;%d&quot;, &amp;target); \/\/ Input the node to search for\n\n    bfs(graph, 0, target, num_nodes); \/\/ Start BFS from node 0\n\n    return 0;\n}\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>Graph Representation:<\/strong>\n<ul class=\"wp-block-list\">\n<li>The graph is represented using an adjacency list, where each vertex points to a list of its neighbors. The <code>Node<\/code> structure is used for the list.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Queue for BFS:<\/strong>\n<ul class=\"wp-block-list\">\n<li>A simple queue structure is implemented to keep track of nodes to be explored. The queue maintains two indices (<code>front<\/code> and <code>rear<\/code>).<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Graph Functions:<\/strong>\n<ul class=\"wp-block-list\">\n<li><strong>createNode<\/strong>: Creates a new node for the adjacency list.<\/li>\n\n\n\n<li><strong>createGraph<\/strong>: Initializes a graph with a specified number of vertices.<\/li>\n\n\n\n<li><strong>addEdge<\/strong>: Adds an edge between two vertices. Since the graph is undirected, it adds an edge in both directions.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>BFS Implementation:<\/strong>\n<ul class=\"wp-block-list\">\n<li>In the <code>bfs<\/code> function, we start from the specified vertex, marking it as visited and enqueueing it.<\/li>\n\n\n\n<li>The algorithm enters a loop where it dequeues a vertex, prints it, and enqueues all its unvisited neighbors.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Main Function:<\/strong>\n<ul class=\"wp-block-list\">\n<li>The <code>main<\/code> function creates a graph with 6 vertices, adds edges, and initiates the BFS starting from vertex <code>0<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Example Input and Output<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Input (Edges of the graph):<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">The edges added to the graph are:<br>0 \u2192 1<br>0 \u2192 2<br>1 \u2192 3<br>1 \u2192 4<br>2 \u2192 4<br>3 \u2192 5<\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Output<\/h4>\n\n\n\n<p>When you run the program, you will see the following output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">yamlCopy code<code>BFS Traversal: 0 1 2 3 4 5 \n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>This program demonstrates the implementation of the BFS algorithm in C. It shows how to traverse a graph level by level, which can be useful in various applications such as finding the shortest path in unweighted graphs or exploring connected components. You can modify the graph structure by changing the edges or the starting vertex to observe different traversal behaviors.<\/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>What is Breadth First Search (BFS)? BFS is a traversal algorithm for graph or tree data structures. It explores nodes level by level, starting from a specified node (often called the source) and moving outward. BFS is commonly used to find the shortest path in an unweighted graph. Key Components of BFS Code Explanation of [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":554,"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-525","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\/525","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\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=525"}],"version-history":[{"count":12,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/525\/revisions"}],"predecessor-version":[{"id":1473,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/525\/revisions\/1473"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/554"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=525"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=525"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=525"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}