{"id":26323,"date":"2017-10-26T21:03:39","date_gmt":"2017-10-26T15:33:39","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26323"},"modified":"2017-10-26T21:03:39","modified_gmt":"2017-10-26T15:33:39","slug":"c-algorithm-check-given-graph-tree-not","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-algorithm-check-given-graph-tree-not\/","title":{"rendered":"C++ 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>C++ \u00a0Programming:<\/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\">\/\/ A C++ Program to check whether a graph is tree or not<br\/>#include&lt;iostream&gt;<br\/>#include &lt;list&gt;<br\/>#include &lt;limits.h&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ Class for an undirected graph<br\/>class Graph<br\/>{<br\/>    int V;    \/\/ No. of vertices<br\/>    list&lt;int&gt; *adj; \/\/ Pointer to an array for adjacency lists<br\/>    bool isCyclicUtil(int v, bool visited[], int parent);<br\/>public:<br\/>    Graph(int V);   \/\/ Constructor<br\/>    void addEdge(int v, int w);   \/\/ to add an edge to graph<br\/>    bool isTree();   \/\/ returns true if graph is tree<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\/>    adj[w].push_back(v); \/\/ Add v to w\u2019s list.<br\/>}<br\/> <br\/>\/\/ A recursive function that uses visited[] and parent to<br\/>\/\/ detect cycle in subgraph reachable from vertex v.<br\/>bool Graph::isCyclicUtil(int v, bool visited[], int parent)<br\/>{<br\/>    \/\/ Mark the current node as visited<br\/>    visited[v] = true;<br\/> <br\/>    \/\/ Recur for all the vertices adjacent to this vertex<br\/>    list&lt;int&gt;::iterator i;<br\/>    for (i = adj[v].begin(); i != adj[v].end(); ++i)<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 current<br\/>        \/\/ 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\/>bool Graph::isTree()<br\/>{<br\/>    \/\/ Mark all the vertices as not visited and not part of <br\/>    \/\/ recursion stack<br\/>    bool *visited = new bool[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 program to test above functions<br\/>int main()<br\/>{<br\/>    Graph g1(5);<br\/>    g1.addEdge(1, 0);<br\/>    g1.addEdge(0, 2);<br\/>    g1.addEdge(0, 3);<br\/>    g1.addEdge(3, 4);<br\/>    g1.isTree()? cout &lt;&lt; &quot;Graph is Tree\\n&quot;:<br\/>                 cout &lt;&lt; &quot;Graph is not Tree\\n&quot;;<br\/> <br\/>    Graph g2(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\/>    g2.isTree()? cout &lt;&lt; &quot;Graph is Tree\\n&quot;:<br\/>                 cout &lt;&lt; &quot;Graph is not Tree\\n&quot;;<br\/> <br\/>    return 0;<br\/>}<\/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>C++ 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":[83515,1,74168,73906],"tags":[78368,76523,76546,76185,76184,76183,78377,76187,76525,78378,76522,78376,78375,78367],"class_list":["post-26323","post","type-post","status-publish","format-standard","hentry","category-c-programming-3","category-coding","category-dfs-and-bfs","category-graph-algorithms","tag-c-program-to-check-whether-the-given-graph-is-tree","tag-cycle-in-directed-graph","tag-detect-cycle-in-directed-graph","tag-detect-cycle-in-directed-graph-in-c","tag-detect-cycle-in-directed-graph-java","tag-detect-cycle-in-undirected-graph","tag-detect-cycle-in-undirected-graph-bfs","tag-detect-cycle-in-undirected-graph-in-c","tag-detect-cycle-in-undirected-graph-java","tag-detect-cycle-in-undirected-graph-using-dfs","tag-find-all-cycles-in-an-undirected-graph","tag-given-an-array-of-integers-print-the-2-elements-with-least-absolute-difference","tag-how-to-check-if-a-directed-graph-is-a-tree","tag-how-to-check-if-a-graph-is-a-tree"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26323","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=26323"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26323\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26323"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26323"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26323"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}