Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C++ Program to Check if an UnDirected Graph is a Tree or Not Using DFS
A graph is a tree if it does not contain any cycle. This is a C++ program to check whether an undirected graph is tree or not.
Algorithm
Begin function cyclicUtil() : A) Mark the current node as visited. B) Recur for all the vertices adjacent to this vertex. C) If an adjacent is not visited, then recur for that adjacent. D) If an adjacent is visited and not parent of current vertex, then there is a cycle. End Begin function cyclic(): A) Mark all the vertices as not visited and not part of recursion stack. B) Call the recursive function cyclicUtil() to detect cycle in differentDFS trees. End
Example
#include#include #include
using namespace std; class G { int n; list *adj; bool CyclicUtil(int v, bool visited[], int par); public: G(int n); //constructor void addEd(int v, int w); bool cyclic(); }; G::G(int n) { this->n = n; adj = new list [n]; } void G::addEd(int v, int u)//to add edges in the graph { adj[v].push_back(u); //add u to v’s list adj[u].push_back(v);//add v to u’s list } //recusive function uses visited[] to detect cycle in subgraph reachable from vertex v: bool G::CyclicUtil(int v, bool visited[], int par) { visited[v] = true; // Mark the current node as visited // Recur for all the vertices adjacent to this vertex list ::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { if (!visited[*i]) //If an adjacent is not visited, then recur for that adjacent { if (CyclicUtil(*i, visited, v)) return true; } // If an adjacent is visited and not parent of current vertex, then there is a cycle. else if (*i != par) return true; } return false; } // to check if the graph is tree or not. bool G ::cyclic() { bool *visited = new bool[n]; // Mark all the vertices as not visited and not part of recursion stack for (int i = 0; i Output
Undirected Graph is a tree
Advertisements
