Depth First Search, Graph
Problem Statement :
Check whether the graph is a tree or not.
Solution Approach :
For a graph to be tree, there should not be any loops and every vertex must be reachable from atleast one other vertex.
This problem can be solved by many ways like Breadth First Search, Depth First Search or Disjoint Set. Below we are going to go through some algorithms for beginners and discuss two of the above mentioned methods to solve this problem.
Method 1 :
The graph must follow these properties:
- If there are
nvertices then there must be
- It should be connected i.e. every vertex can be reached with atleast one other vertex.
In trees, every node/vertex is connected to atleast one other vertex. Also the total number of edges is also
Method 2 :
The another way of checking our graph whether it is a tree or not that it should have following properties:
- It must not contain any cycle.
- It must be connected.
As, we can see this approach is almost similar to the approach in method
1, our goal is to make sure that our graph has no loops or in other words it has exactly
n-1edges and must be connected. By this way we can ensure our graph is a tree, otherwise not. Refer to the example below for better understanding.
See C++ implementation below.
- For each call, for some vertex
v) ), we will mark the vertex
vas visited (
- Iterate for all the adjacent vertices of
vand for every adjacent vertex
a, do following :
ais not visited i.e
recursively call dfs (
The time complexity of the first method is represented in the form of
Vis the number of verices and
Eis the number of edges.
The space complexity of the algorithm is