Given an undirected graph, the task is to if adding an edge makes the graph cyclic or not.
In an Undirected graph, a cycle is a path of edges that connects a sequence of vertices back to itself. In other words, a cycle is a closed loop of edges that allows you to traverse the graph and return to the starting vertex.
For example:
A --- B
/ \
C D
\ /
E --- F
In this graph, there are several cycles that can be formed by following different sequences of edges. For example, the sequence of edges A-B-D-F-E-C-A forms a cycle, as does the sequence B-D-F-E-C-A-B.
Naive approach: The basic way to solve the problem is as follows:
Use depth-first Search to detect the cycle during the insertion of the nodes. If while traversing we reach a node that is already visited. This indicates that cycle is formed.
Follow the steps below to solve the problem:
- Create a detect cycle function that takes a graph and a new node as input.
- Define a dfs function that takes a graph, a node, a set of visited nodes, and a search path array as input.
- In the detectCycle function, initialize an empty set of visited nodes and an empty search path array.
- Call the dfs function, starting from the new node, and passing the graph, visited nodes, and search path array as arguments.
- Return the result of the dfs function.
- In the dfs function, mark the current node as visited and add it to the search path array.
- Check all the neighbors of the current node.
- For each neighbor:
- If the neighbor is already visited, check if it is in the current search path.
- If it is, then we have found a cycle, so return true.
- If it is not visited, continue the DFS from that node. If the DFS returns true, then return true as well.
- Remove the current node from the search path array.
- Return false.
Below is the implementation of the above approach:Recommended Practice
Please try your approach on IDE first, before moving on to the solution.
Try It!
Time complexity: O(V+E), where V is the number of vertices (or nodes) in the graph, and E is the number of edges in the graph.
Auxiliary Space: O(V)
Efficient Approach: The above approach can be optimized based on the following idea:
- The approach used in the above code is a union-find-based approach to detect cycles in the graph.
- The find() method is used to find the root of the tree representing a given node, and
- the addEdge() method uses the find() method to find the roots of the trees representing the two nodes being connected by the edge.
- If the roots are the same, it means that the two nodes are already in the same connected component, and adding the edge would create a cycle in the graph.
- If the roots are different, the addEdge() method merges the two connected components by attaching the root of the smaller tree to the root of the larger tree.
Below is the implementation of the above approach:
Time complexity: O(E log V)
Auxiliary Space: O(V)