![]() |
VOOZH | about |
Given an undirected graph, the task is to choose a direction for each edge so that the resulting directed graph is acyclic. You can print any valid solution.
Input: n = 3, m = 3, edge = {{1, 2}, {2, 3}, {3, 1}}
Output:
1 2
2 3
1 3
Explanation: Connecting the graph in this manner will result in directed acyclic graph.Input: n = 4, m = 4, edge = {{1, 2}, {2, 3}, {3, 4}, {4, 1}}
Output:
1 2
2 3
3 4
1 4Explanation: Connecting the graph in this manner will result in directed acyclic graph.
Approach: To solve the problem, follow the idea below:
The idea is to direct the edges from smaller vertex to largest one, to make the graph acyclic. It ensures that all edges are directed in a way that prevents cycles. Since each edge is directed from a smaller node to a larger node, it’s impossible to go back to a smaller node from a larger node, which prevents any cycles from forming.
Step-by-step algorithm:
Below is the implementation of the algorithm:
1 2 2 3 1 3
Time Complexity: O(n), where n is the number of nodes.
Auxiliary Space: O(1)