VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-acyclic-graph-edges/

⇱ CSES Solutions - Acyclic Graph Edges - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Acyclic Graph Edges

Last Updated : 25 Jun, 2024

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.

Example:

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 4

Explanation: 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:

  • Loop through each edge.
  • For each edge, check if the first vertex is greater than the second vertex.
  • If so, swap the vertices to ensure the edge is directed from the smaller vertex to the larger vertex.

Below is the implementation of the algorithm:


Output
1 2
2 3
1 3

Time Complexity: O(n), where n is the number of nodes.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: