Given a directed and unweighted graph consisting of N vertices and an array arr where ith vertex have a directed edge to arr[i]. The task is to find the number of ways to change the direction of edges such that the given graph is acyclic.
Approach: The idea is to check whether the Connected Components form a cycle or not.
- If the component is a path, then however we orient the edges we won’t form a cycle.
- If the component has a cycle with N edges, then there are 2N ways to arrange all the edges out of which only 2 ways are going to form a cycle. So there are (2N – 2) ways to change the edges so that graph becomes acyclic.
- Using Depth First Search(DFS) traversal find the cycles in the given graph and number of vertices associated with each cycle.
- After DFS traversal, the total number of ways to change the direction of edges is the product of the following:
- Number of ways form by each cycle of X vertices is given by (2X – 2).
- Number of ways form by each path of Y vertices is given by (2Y).
Below is the implementation of the above approach:
Time Complexity : O(V + E)
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Assign directions to edges so that the directed graph remains acyclic
- Ways to Remove Edges from a Complete Graph to make Odd Edges
- Count number of edges in an undirected graph
- Maximum number of edges that N-vertex graph can have such that graph is Triangle free | Mantel's Theorem
- Clone a Directed Acyclic Graph
- Shortest Path in Directed Acyclic Graph
- All Topological Sorts of a Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph | Set 2
- Longest Path in a Directed Acyclic Graph
- DFS for a n-ary tree (acyclic graph) represented as adjacency list
- Count total ways to reach destination from source in an undirected Graph
- Longest path in a directed Acyclic graph | Dynamic Programming
- Calculate number of nodes between two vertices in an acyclic Graph by Disjoint Union method
- Level order traversal with direction change after every two levels | Recursive Approach
- All vertex pairs connected with exactly k edges in a graph
- Path with minimum XOR sum of edges in a directed graph
- Minimum number of edges between two vertices of a Graph
- Minimum number of edges between two vertices of a graph using DFS
- Number of Simple Graph with N Vertices and M Edges
- Maximum number of edges in Bipartite graph
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : chitranayal