{"id":25837,"date":"2017-10-25T20:57:26","date_gmt":"2017-10-25T15:27:26","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25837"},"modified":"2017-10-25T20:57:26","modified_gmt":"2017-10-25T15:27:26","slug":"breadth-first-traversal-bfs-graph","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/breadth-first-traversal-bfs-graph\/","title":{"rendered":"Cpp algorithm &#8211; Breadth First Traversal or BFS for a Graph"},"content":{"rendered":"<p><a href=\"http:\/\/en.wikipedia.org\/wiki\/Breadth-first_search\" target=\"_blank\" rel=\"noopener\">Breadth First Traversal<\/a>\u00a0for a graph is similar to Breadth First Traversal of a tree.<span id=\"more-18382\"><\/span> The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is assumed that all vertices are reachable from the starting vertex.<br \/>\nFor example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don\u2019t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Breadth First Traversal of the following graph is 2, 0, 3, 1.<\/p>\n<p>Following are C++ and Java implementations of simple Breadth First Traversal from a given source.<\/p>\n<p>The C++ implementation uses <a href=\"http:\/\/en.wikipedia.org\/wiki\/Adjacency_list\" target=\"_blank\" rel=\"noopener\">adjacency list representation<\/a> of graphs. <a href=\"http:\/\/en.wikipedia.org\/wiki\/Standard_Template_Library\" target=\"_blank\" rel=\"noopener\">STL<\/a>\u2018s <a href=\"http:\/\/www.yolinux.com\/TUTORIALS\/LinuxTutorialC++STL.html#LIST\" target=\"_blank\" rel=\"noopener\">list container<\/a> is used to store lists of adjacent nodes and queue of nodes needed for BFS traversal.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>C++ Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ Program to print BFS traversal from a given source vertex. BFS(int s) <br\/>\/\/ traverses vertices reachable from s.<br\/>#include&lt;iostream&gt;<br\/>#include &lt;list&gt;<br\/> <br\/>using namespace std;<br\/> <br\/>\/\/ This class represents a directed graph using adjacency list representation<br\/>class Graph<br\/>{<br\/>    int V;    \/\/ No. of vertices<br\/>    list&lt;int&gt; *adj;    \/\/ Pointer to an array containing adjacency lists<br\/>public:<br\/>    Graph(int V);  \/\/ Constructor<br\/>    void addEdge(int v, int w); \/\/ function to add an edge to graph<br\/>    void BFS(int s);  \/\/ prints BFS traversal from a given source s<br\/>};<br\/> <br\/>Graph::Graph(int V)<br\/>{<br\/>    this-&gt;V = V;<br\/>    adj = new list&lt;int&gt;[V];<br\/>}<br\/> <br\/>void Graph::addEdge(int v, int w)<br\/>{<br\/>    adj[v].push_back(w); \/\/ Add w to v\u2019s list.<br\/>}<br\/> <br\/>void Graph::BFS(int s)<br\/>{<br\/>    \/\/ Mark all the vertices as not visited<br\/>    bool *visited = new bool[V];<br\/>    for(int i = 0; i &lt; V; i++)<br\/>        visited[i] = false;<br\/> <br\/>    \/\/ Create a queue for BFS<br\/>    list&lt;int&gt; queue;<br\/> <br\/>    \/\/ Mark the current node as visited and enqueue it<br\/>    visited[s] = true;<br\/>    queue.push_back(s);<br\/> <br\/>    \/\/ &#039;i&#039; will be used to get all adjacent vertices of a vertex<br\/>    list&lt;int&gt;::iterator i;<br\/> <br\/>    while(!queue.empty())<br\/>    {<br\/>        \/\/ Dequeue a vertex from queue and print it<br\/>        s = queue.front();<br\/>        cout &lt;&lt; s &lt;&lt; &quot; &quot;;<br\/>        queue.pop_front();<br\/> <br\/>        \/\/ Get all adjacent vertices of the dequeued vertex s<br\/>        \/\/ If a adjacent has not been visited, then mark it visited<br\/>        \/\/ and enqueue it<br\/>        for(i = adj[s].begin(); i != adj[s].end(); ++i)<br\/>        {<br\/>            if(!visited[*i])<br\/>            {<br\/>                visited[*i] = true;<br\/>                queue.push_back(*i);<br\/>            }<br\/>        }<br\/>    }<br\/>}<br\/> <br\/>\/\/ Driver program to test methods of graph class<br\/>int main()<br\/>{<br\/>    \/\/ Create a graph given in the above diagram<br\/>    Graph g(4);<br\/>    g.addEdge(0, 1);<br\/>    g.addEdge(0, 2);<br\/>    g.addEdge(1, 2);<br\/>    g.addEdge(2, 0);<br\/>    g.addEdge(2, 3);<br\/>    g.addEdge(3, 3);<br\/> <br\/>    cout &lt;&lt; &quot;Following is Breadth First Traversal &quot;<br\/>         &lt;&lt; &quot;(starting from vertex 2) \\n&quot;;<br\/>    g.BFS(2);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Following is Breadth First Traversal (starting from vertex 2)\r\n2 0 3 1\r\n<\/pre>\n<p>Note that the above code traverses only the vertices reachable from a given source vertex. All the vertices may not be reachable from a given vertex (example Disconnected graph). To print all the vertices, we can modify the BFS function to do traversal starting from all nodes one by one (Like the <a href=\"http:\/\/www.geeksforgeeks.org\/archives\/18212\" target=\"_blank\" rel=\"noopener\">DFS modified version<\/a>) .<\/p>\n<p>Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Cpp Algorithm &#8211; Breadth First Traversal or BFS for a Graph &#8211; Graph Algorithms &#8211; Breadth First Traversal for a graph is similar to Breadth First Traversal.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[83567,74168,73906],"tags":[75740,75741,75743,75744,75739,75737,75742,75738],"class_list":["post-25837","post","type-post","status-publish","format-standard","hentry","category-cpp-algorithm","category-dfs-and-bfs","category-graph-algorithms","tag-breadth-first-search-algorithm","tag-breadth-first-search-example","tag-breadth-first-search-java","tag-breadth-first-search-program-in-c","tag-breadth-first-search-pseudocode","tag-c-program-of-breadth-first-search-in-a-graph","tag-depth-first-search","tag-dfs-c"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25837","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25837"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25837\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25837"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25837"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25837"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}