{"id":25902,"date":"2017-10-25T21:19:30","date_gmt":"2017-10-25T15:49:30","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25902"},"modified":"2017-10-25T21:19:30","modified_gmt":"2017-10-25T15:49:30","slug":"python-algorithm-depth-first-traversal-dfs-graph","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-algorithm-depth-first-traversal-dfs-graph\/","title":{"rendered":"Python Algorithm &#8211; Depth First Traversal or DFS for a Graph"},"content":{"rendered":"<p>Depth First Traversal\u00a0for a graph is similar to Depth First Traversal of a tree. 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. <span id=\"more-18212\"><\/span><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 Depth First Traversal of the following graph is 2, 0, 1, 3<strong>.<\/strong><\/p>\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\"># Python program to print DFS traversal from a<br\/># given given graph<br\/>from collections import defaultdict<br\/> <br\/># This class represents a directed graph using<br\/># adjacency 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\/>    # A function used by DFS<br\/>    def DFSUtil(self,v,visited):<br\/> <br\/>        # Mark the current node as visited and print it<br\/>        visited[v]= True<br\/>        print v,<br\/> <br\/>        # Recur for all the vertices adjacent to this vertex<br\/>        for i in self.graph[v]:<br\/>            if visited[i] == False:<br\/>                self.DFSUtil(i, visited)<br\/> <br\/> <br\/>    # The function to do DFS traversal. It uses<br\/>    # recursive DFSUtil()<br\/>    def DFS(self,v):<br\/> <br\/>        # Mark all the vertices as not visited<br\/>        visited = [False]*(len(self.graph))<br\/> <br\/>        # Call the recursive helper function to print<br\/>        # DFS traversal<br\/>        self.DFSUtil(v,visited)<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 DFS from (starting from vertex 2)&quot;<br\/>g.DFS(2)<br\/> <br\/># This code is contributed by Neelam Yadav<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Following is Depth First Traversal (starting from vertex 2)\r\n2 0 1 3\r\n\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 do complete DFS traversal of such graphs, we must call DFSUtil() for every vertex. Also, before calling DFSUtil(), we should check if it is already printed by some other call of DFSUtil(). Following implementation does the complete graph traversal even if the nodes are unreachable.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>The differences from the above code are highlighted in the below code.<\/p>\n<p><strong>Python Programming:<\/strong><\/p>\n<div class=\"responsive-tabs-wrapper\"><\/div>\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\"># Python program to print DFS traversal for complete graph<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\/>    # A function used by DFS<br\/>    def DFSUtil(self, v, visited):<br\/> <br\/>        # Mark the current node as visited and print it<br\/>        visited[v]= True<br\/>        print v,<br\/> <br\/>        # Recur for all the vertices adjacent to<br\/>        # this vertex<br\/>        for i in self.graph[v]:<br\/>            if visited[i] == False:<br\/>                self.DFSUtil(i, visited)<br\/> <br\/> <br\/>    # The function to do DFS traversal. It uses<br\/>    # recursive DFSUtil()<br\/>    def DFS(self):<br\/>        V = len(self.graph)  #total vertices<br\/> <br\/>        # Mark all the vertices as not visited<br\/>        visited =[False]*(V)<br\/> <br\/>        # Call the recursive helper function to print<br\/>        # DFS traversal starting from all vertices one<br\/>        # by one<br\/>        for i in range(V):<br\/>            if visited[i] == False:<br\/>                self.DFSUtil(i, visited)<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 Depth First Traversal&quot;<br\/>g.DFS()<br\/> <br\/># This code is contributed by Neelam Yadav<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Following is Depth First Traversal\r\n0 1 2 3<\/pre>\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> Python Algorithm &#8211; Depth First Traversal or DFS for a Graph &#8211; Graph Algorithms &#8211; Depth First Traversal for a graph is similar to Depth 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":[1,74168,73906,4148],"tags":[75954,75951,75904,75905,75952,75949,75953,75950],"class_list":["post-25902","post","type-post","status-publish","format-standard","hentry","category-coding","category-dfs-and-bfs","category-graph-algorithms","category-python","tag-breadth-first-search-c","tag-breadth-first-search-python-code","tag-depth-first-search-algorithm","tag-depth-first-search-c","tag-depth-first-search-java","tag-depth-first-search-python","tag-depth-first-search-python-stack","tag-python-depth-first-search-tree"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25902","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=25902"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25902\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25902"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25902"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25902"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}