# Count number of trees in a forest

Given n nodes of a forest (collection of trees), find the number of trees in the forest.

Examples :

```Input :  edges[] = {0, 1}, {0, 2}, {3, 4}
Output : 2
Explanation : There are 2 trees
0       3
/
1   2       4
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach :
1. Apply DFS on every node.
2. Increment count by one if every connected node is visited from one source.
3. Again perform DFS traversal if some nodes yet not visited.
4. Count will give the number of trees in forest.

## C++

 `// CPP program to count number of trees in ` `// a forest. ` `#include ` `using` `namespace` `std; ` ` `  `// A utility function to add an edge in an ` `// undirected graph. ` `void` `addEdge(vector<``int``> adj[], ``int` `u, ``int` `v) ` `{ ` `    ``adj[u].push_back(v); ` `    ``adj[v].push_back(u); ` `} ` ` `  `// A utility function to do DFS of graph ` `// recursively from a given vertex u. ` `void` `DFSUtil(``int` `u, vector<``int``> adj[], ` `                    ``vector<``bool``> &visited) ` `{ ` `    ``visited[u] = ``true``; ` `    ``for` `(``int` `i=0; i adj[], ``int` `V) ` `{ ` `    ``vector<``bool``> visited(V, ``false``); ` `    ``int` `res = 0; ` `    ``for` `(``int` `u=0; u adj[V]; ` `    ``addEdge(adj, 0, 1); ` `    ``addEdge(adj, 0, 2); ` `    ``addEdge(adj, 3, 4); ` `    ``cout << countTrees(adj, V); ` `    ``return` `0; ` `} `

## Python3

# Python3 program to count number
# of trees in a forest.

# A utility function to add an
# edge in an undirected graph.

# A utility function to do DFS of graph
# recursively from a given vertex u.
visited[u] = True

# Returns count of tree is the
# forest given as adjacency list.
visited = [False] * V
res = 0
for u in range(V):
if (visited[u] == False):
res += 1
return res

# Driver code
if __name__ == ‘__main__’:

V = 5
adj = [[] for i in range(V)]

# This code is contributed by PranchalK

Output:

```2
```

Time Complexity : O(V + E)

## tags:

Graph DFS DFS Graph