{"id":26332,"date":"2017-10-26T21:02:32","date_gmt":"2017-10-26T15:32:32","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26332"},"modified":"2017-10-26T21:02:32","modified_gmt":"2017-10-26T15:32:32","slug":"java-algorithm-check-given-graph-tree-not","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-algorithm-check-given-graph-tree-not\/","title":{"rendered":"Java Algorithm &#8211; Check if a given graph is tree or not"},"content":{"rendered":"<p>Write a function that returns true if a given undirected graph is tree and false otherwise. For example, the following graph is a tree.<span id=\"more-142562\"><\/span><\/p>\n<p>&nbsp;<\/p>\n<p>But the following graph is not a tree.<\/p>\n<p>An undirected graph is tree if it has following properties.<br \/>\n1) There is no cycle.<br \/>\n2) The graph is connected.<\/p>\n<p>For an undirected graph we can either use BFS or DFS to detect above two properties.<\/p>\n<p><strong>How to detect cycle in an undirected graph?<\/strong><br \/>\nWe can either use BFS or DFS. For every visited vertex \u2018v\u2019, if there is an adjacent \u2018u\u2019 such that u is already visited and u is not parent of v, then there is a cycle in graph. If we don\u2019t find such an adjacent for any vertex, we say that there is no cycle (See Detect cycle in an undirected graph for more details).<\/p>\n<p><strong>How to check for connectivity?<\/strong><br \/>\nSince the graph is undirected, we can start BFS or DFS from any vertex and check if all vertices are reachable or not. If all vertices are reachable, then graph is connected, otherwise not.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Java \u00a0Programming:<\/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\">\/\/ A Java Program to check whether a graph is tree or not<br\/>import java.io.*;<br\/>import java.util.*;<br\/> <br\/>\/\/ This class represents a directed graph using adjacency<br\/>\/\/ list representation<br\/>class Graph<br\/>{<br\/>    private int V;   \/\/ No. of vertices<br\/>    private LinkedList&lt;Integer&gt; adj[]; \/\/Adjacency List<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);<br\/>        adj[w].add(v);<br\/>    }<br\/> <br\/>    \/\/ A recursive function that uses visited[] and parent<br\/>    \/\/ to detect cycle in subgraph reachable from vertex v.<br\/>    Boolean isCyclicUtil(int v, Boolean visited[], int parent)<br\/>    {<br\/>        \/\/ Mark the current node as visited<br\/>        visited[v] = true;<br\/>        Integer i;<br\/> <br\/>        \/\/ Recur for all the vertices adjacent to this vertex<br\/>        Iterator&lt;Integer&gt; it = adj[v].iterator();<br\/>        while (it.hasNext())<br\/>        {<br\/>            i = it.next();<br\/> <br\/>            \/\/ If an adjacent is not visited, then recur for<br\/>            \/\/ that adjacent<br\/>            if (!visited[i])<br\/>            {<br\/>                if (isCyclicUtil(i, visited, v))<br\/>                    return true;<br\/>            }<br\/> <br\/>            \/\/ If an adjacent is visited and not parent of <br\/>            \/\/ current vertex, then there is a cycle.<br\/>            else if (i != parent)<br\/>               return true;<br\/>        }<br\/>        return false;<br\/>    }<br\/> <br\/>    \/\/ Returns true if the graph is a tree, else false.<br\/>    Boolean isTree()<br\/>    {<br\/>        \/\/ Mark all the vertices as not visited and not part<br\/>        \/\/ of recursion stack<br\/>        Boolean visited[] = new Boolean[V];<br\/>        for (int i = 0; i &lt; V; i++)<br\/>            visited[i] = false;<br\/> <br\/>        \/\/ The call to isCyclicUtil serves multiple purposes<br\/>        \/\/ It returns true if graph reachable from vertex 0<br\/>        \/\/ is cyclcic. It also marks all vertices reachable<br\/>        \/\/ from 0.<br\/>        if (isCyclicUtil(0, visited, -1))<br\/>            return false;<br\/> <br\/>        \/\/ If we find a vertex which is not reachable from 0<br\/>        \/\/ (not marked by isCyclicUtil(), then we return false<br\/>        for (int u = 0; u &lt; V; u++)<br\/>            if (!visited[u])<br\/>                return false;<br\/> <br\/>        return true;<br\/>    }<br\/> <br\/>    \/\/ Driver method<br\/>    public static void main(String args[])<br\/>    {<br\/>        \/\/ Create a graph given in the above diagram<br\/>        Graph g1 = new Graph(5);<br\/>        g1.addEdge(1, 0);<br\/>        g1.addEdge(0, 2);<br\/>        g1.addEdge(0, 3);<br\/>        g1.addEdge(3, 4);<br\/>        if (g1.isTree())<br\/>            System.out.println(&quot;Graph is Tree&quot;);<br\/>        else<br\/>            System.out.println(&quot;Graph is not Tree&quot;);<br\/> <br\/>        Graph g2 = new Graph(5);<br\/>        g2.addEdge(1, 0);<br\/>        g2.addEdge(0, 2);<br\/>        g2.addEdge(2, 1);<br\/>        g2.addEdge(0, 3);<br\/>        g2.addEdge(3, 4);<br\/> <br\/>        if (g2.isTree())<br\/>            System.out.println(&quot;Graph is Tree&quot;);<br\/>        else<br\/>            System.out.println(&quot;Graph is not Tree&quot;);<br\/> <br\/>    }<br\/>}<br\/>\/\/ This code is contributed by Aakash Hasija<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Graph is Tree\r\nGraph is not Tree<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Algorithm &#8211; Check if a given graph is tree or not &#8211;  Graph Algorithm &#8211; Write a function that returns true if a given undirected graph is 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,1,74168,73906,2139],"tags":[78368,78369,76188,76546,76186,76185,76184,76189,76183,76187,78370,76190,78367],"class_list":["post-26332","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-coding","category-dfs-and-bfs","category-graph-algorithms","category-java","tag-c-program-to-check-whether-the-given-graph-is-tree","tag-c-program-to-detect-cycle-in-a-graph","tag-detect-cycle-in-a-graph-c-code","tag-detect-cycle-in-directed-graph","tag-detect-cycle-in-directed-graph-c","tag-detect-cycle-in-directed-graph-in-c","tag-detect-cycle-in-directed-graph-java","tag-detect-cycle-in-graph-using-bfs","tag-detect-cycle-in-undirected-graph","tag-detect-cycle-in-undirected-graph-in-c","tag-dfs-pseudocode","tag-find-all-cycles-in-a-directed-graph","tag-how-to-check-if-a-graph-is-a-tree"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26332","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=26332"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26332\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26332"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26332"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26332"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}