{"id":25857,"date":"2017-10-25T21:24:50","date_gmt":"2017-10-25T15:54:50","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25857"},"modified":"2017-10-25T22:10:58","modified_gmt":"2017-10-25T16:40:58","slug":"25857-2","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/25857-2\/","title":{"rendered":"Python algorithm &#8211; Breadth First Traversal or BFS for a Graph"},"content":{"rendered":"<p>Breadth First Traversal\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>PYTHON Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Program to print BFS traversal from a given source<br\/># vertex. BFS(int s) traverses vertices reachable<br\/># from s.<br\/>from collections import defaultdict<br\/> <br\/># This class represents a directed graph using adjacency<br\/># list representation<br\/>class Graph:<br\/> <br\/>    # Constructor<br\/>    def __init__(self):<br\/> <br\/>        # default dictionary to store graph<br\/>        self.graph = defaultdict(list)<br\/> <br\/>    # function to add an edge to graph<br\/>    def addEdge(self,u,v):<br\/>        self.graph[u].append(v)<br\/> <br\/>    # Function to print a BFS of graph<br\/>    def BFS(self, s):<br\/> <br\/>        # Mark all the vertices as not visited<br\/>        visited = [False]*(len(self.graph))<br\/> <br\/>        # Create a queue for BFS<br\/>        queue = []<br\/> <br\/>        # Mark the source node as visited and enqueue it<br\/>        queue.append(s)<br\/>        visited[s] = True<br\/> <br\/>        while queue:<br\/> <br\/>            # Dequeue a vertex from queue and print it<br\/>            s = queue.pop(0)<br\/>            print s,<br\/> <br\/>            # Get all adjacent vertices of the dequeued<br\/>            # vertex s. If a adjacent has not been visited,<br\/>            # then mark it visited and enqueue it<br\/>            for i in self.graph[s]:<br\/>                if visited[i] == False:<br\/>                    queue.append(i)<br\/>                    visited[i] = True<br\/> <br\/> <br\/># Driver code<br\/># Create a graph given in the above diagram<br\/>g = Graph()<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\/>print &quot;Following is Breadth First Traversal (starting from vertex 2)&quot;<br\/>g.BFS(2)<br\/> <br\/># This code is contributed by Neelam Yadav<\/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<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python algorithm &#8211; Breadth First Traversal or BFS for a Graph &#8211; Breadth First Traversal for a graph is similar to Breadth First Traversal of a tree<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,74168,73906,4148],"tags":[83579,80887,83581,83580,83578,82368,75954,75757,75743,75739,82371,82370,75742,80881],"class_list":["post-25857","post","type-post","status-publish","format-standard","hentry","category-coding","category-dfs-and-bfs","category-graph-algorithms","category-python","tag-bfs-code-in-c","tag-bfs-example","tag-bfs-program-in-c","tag-bfs-program-in-c-using-adjacency-list","tag-bfs-python","tag-breadth-first-search-algorithm-with-example","tag-breadth-first-search-c","tag-breadth-first-search-in-c","tag-breadth-first-search-java","tag-breadth-first-search-pseudocode","tag-breadth-first-search-tree","tag-breadth-first-search-vs-depth-first-search","tag-depth-first-search","tag-depth-first-search-algorithm-with-example"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25857","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=25857"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25857\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25857"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25857"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25857"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}