{"id":25891,"date":"2017-10-25T21:13:05","date_gmt":"2017-10-25T15:43:05","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25891"},"modified":"2017-10-25T21:13:05","modified_gmt":"2017-10-25T15:43:05","slug":"java-algorithm-depth-first-traversal-dfs-graph","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-algorithm-depth-first-traversal-dfs-graph\/","title":{"rendered":"Java 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>Java Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to print DFS traversal from a given given graph<br\/>import java.io.*;<br\/>import java.util.*;<br\/> <br\/>\/\/ This class represents a directed graph using adjacency list<br\/>\/\/ representation<br\/>class Graph<br\/>{<br\/>    private int V;   \/\/ No. of vertices<br\/> <br\/>    \/\/ Array  of lists for Adjacency List Representation<br\/>    private LinkedList&lt;Integer&gt; adj[];<br\/> <br\/>    \/\/ Constructor<br\/>    Graph(int v)<br\/>    {<br\/>        V = v;<br\/>        adj = new LinkedList[v];<br\/>        for (int i=0; i&lt;v; ++i)<br\/>            adj[i] = new LinkedList();<br\/>    }<br\/> <br\/>    \/\/Function to add an edge into the graph<br\/>    void addEdge(int v, int w)<br\/>    {<br\/>        adj[v].add(w);  \/\/ Add w to v&#039;s list.<br\/>    }<br\/> <br\/>    \/\/ A function used by DFS<br\/>    void DFSUtil(int v,boolean visited[])<br\/>    {<br\/>        \/\/ Mark the current node as visited and print it<br\/>        visited[v] = true;<br\/>        System.out.print(v+&quot; &quot;);<br\/> <br\/>        \/\/ Recur for all the vertices adjacent to this vertex<br\/>        Iterator&lt;Integer&gt; i = adj[v].listIterator();<br\/>        while (i.hasNext())<br\/>        {<br\/>            int n = i.next();<br\/>            if (!visited[n])<br\/>                DFSUtil(n, visited);<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ The function to do DFS traversal. It uses recursive DFSUtil()<br\/>    void DFS(int v)<br\/>    {<br\/>        \/\/ Mark all the vertices as not visited(set as<br\/>        \/\/ false by default in java)<br\/>        boolean visited[] = new boolean[V];<br\/> <br\/>        \/\/ Call the recursive helper function to print DFS traversal<br\/>        DFSUtil(v, visited);<br\/>    }<br\/> <br\/>    public static void main(String args[])<br\/>    {<br\/>        Graph g = new Graph(4);<br\/> <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\/>        System.out.println(&quot;Following is Depth First Traversal &quot;+<br\/>                           &quot;(starting from vertex 2)&quot;);<br\/> <br\/>        g.DFS(2);<br\/>    }<br\/>}<br\/>\/\/ This code is contributed by Aakash Hasija<\/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>Java 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-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to print DFS traversal from a given given graph<br\/>import java.io.*;<br\/>import java.util.*;<br\/> <br\/>\/\/ This class represents a directed graph using adjacency list<br\/>\/\/ representation<br\/>class Graph<br\/>{<br\/>    private int V;   \/\/ No. of vertices<br\/> <br\/>    \/\/ Array  of lists for Adjacency List Representation<br\/>    private LinkedList&lt;Integer&gt; adj[];<br\/> <br\/>    \/\/ Constructor<br\/>    Graph(int v)<br\/>    {<br\/>        V = v;<br\/>        adj = new LinkedList[v];<br\/>        for (int i=0; i&lt;v; ++i)<br\/>            adj[i] = new LinkedList();<br\/>    }<br\/> <br\/>    \/\/Function to add an edge into the graph<br\/>    void addEdge(int v, int w)<br\/>    {<br\/>        adj[v].add(w);  \/\/ Add w to v&#039;s list.<br\/>    }<br\/> <br\/>    \/\/ A function used by DFS<br\/>    void DFSUtil(int v,boolean visited[])<br\/>    {<br\/>        \/\/ Mark the current node as visited and print it<br\/>        visited[v] = true;<br\/>        System.out.print(v+&quot; &quot;);<br\/> <br\/>        \/\/ Recur for all the vertices adjacent to this vertex<br\/>        Iterator&lt;Integer&gt; i = adj[v].listIterator();<br\/>        while (i.hasNext())<br\/>        {<br\/>            int n = i.next();<br\/>            if (!visited[n])<br\/>                DFSUtil(n,visited);<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ The function to do DFS traversal. It uses recursive DFSUtil()<br\/>    void DFS()<br\/>    {<br\/>        \/\/ Mark all the vertices as not visited(set as<br\/>        \/\/ false by default in java)<br\/>        boolean visited[] = new boolean[V];<br\/> <br\/>        \/\/ Call the recursive helper function to print DFS traversal<br\/>        \/\/ starting from all vertices one by one<br\/>        for (int i=0; i&lt;V; ++i)<br\/>            if (visited[i] == false)<br\/>                DFSUtil(i, visited);<br\/>    }<br\/> <br\/>    public static void main(String args[])<br\/>    {<br\/>        Graph g = new Graph(4);<br\/> <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\/>        System.out.println(&quot;Following is Depth First Traversal&quot;);<br\/> <br\/>        g.DFS();<br\/>    }<br\/>}<br\/>\/\/ This code is contributed by Aakash Hasija<\/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>Java Algorithm &#8211; Depth First Traversal or DFS for a Graph -Graph Algorithms -Depth First Traversal for a graph is similar to Depth 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":[69969,74168,73906,2139],"tags":[75902,75906,75904,75905,75901,75900,75903,74286],"class_list":["post-25891","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-dfs-and-bfs","category-graph-algorithms","category-java","tag-bfs-java","tag-breadth-first-search","tag-depth-first-search-algorithm","tag-depth-first-search-c","tag-depth-first-search-java-stack","tag-depth-first-search-tree-java","tag-dfs-java-recursive","tag-graph-traversal-in-data-structure"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25891","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=25891"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25891\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25891"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25891"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25891"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}