Given a graph with both directed and undirected edges. It is given that the directed edges don’t form cycle. How to assign directions to undirected edges so that the graph (with all directed edges) remains acyclic even after the assignment?

For example, in the below graph, blue edges don’t have directions.

**We strongly recommend to minimize your browser and try this yourself first.**

The idea is to use Topological Sorting. Following are two steps used in the algorithm.

**1)** Consider the subgraph with directed edges only and find topological sorting of the subgraph. In the above example, topological sorting is {0, 5, 1, 2, 3, 4}. Below diagram shows topological sorting for the above example graph.

**2) **Use above topological sorting to assign directions to undirected edges. For every undirected edge (u, v), assign it direction from u to v if u comes before v in topological sorting, else assign it direction from v to u.

Below diagram shows assigned directions in the example graph.

Source: http://courses.csail.mit.edu/6.006/oldquizzes/solutions/q2-f2009-sol.pdf

This article is contributed by **Aditya Agrawal**. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Shortest Path in Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph
- All Topological Sorts of a Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph | Set 2
- Clone a Directed Acyclic Graph
- Number of paths from source to destination in a directed acyclic graph
- Longest path in a directed Acyclic graph | Dynamic Programming
- Minimum time taken by each job to be completed given by a Directed Acyclic Graph
- Minimum number of edges required to be removed from an Undirected Graph to make it acyclic
- Count ways to change direction of edges such that graph becomes acyclic
- Maximum edges that can be added to DAG so that is remains DAG
- Shortest path with exactly k edges in a directed and weighted graph
- Minimum edges to be added in a directed graph so that any node can be reachable from a given node
- Check if incoming edges in a vertex of directed graph is equal to vertex itself or not
- Shortest path with exactly k edges in a directed and weighted graph | Set 2
- Path with minimum XOR sum of edges in a directed graph
- Minimum edges required to make a Directed Graph Strongly Connected
- Ways to Remove Edges from a Complete Graph to make Odd Edges
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Convert undirected connected graph to strongly connected directed graph