Given an undirected graph with N vertices and M edges and no self loops or multiple edges. The task is to convert the given undirected graph into a directed graph such that there is no path of length greater than 1. If it is possible to make such a graph then print two space-separated integers u and v in M lines where u, v denotes source and destination vertices respectively. If not possible then print -1.
For the given graph it is not possible to get a directed graph
such that there is no path of length greater than 1
Approach: Let suppose the graph contains a cycle of odd length. It means that some two consecutive edges of this cycle will be oriented in the same way and will form a path of length two. Then the answer is -1.
And if the graph contains no cycles of odd length. Then it is bipartite. Let’s color it and see what we got. We got some vertices in the left part, some vertices in the right part and all edges connecting vertices from different parts. Let’s orient all edges such that they will go from the left part to the right part.
Below is the implementation of the above approach:
1 2 1 3 1 4
- Eulerian Path in undirected graph
- Find if there is a path between two vertices in a directed graph
- Longest Path in a Directed Acyclic Graph
- Longest Path in a Directed Acyclic Graph | Set 2
- Shortest Path in Directed Acyclic Graph
- Eulerian path and circuit for undirected graph
- Shortest path with exactly k edges in a directed and weighted graph
- Longest path in a directed Acyclic graph | Dynamic Programming
- Cycles of length n in an undirected and connected graph
- Hierholzer's Algorithm for directed graph
- Check if a directed graph is connected or not
- Detect Cycle in a Directed Graph
- Detect Cycle in a Directed Graph using BFS
- Euler Circuit in a Directed Graph
- Clone a Directed Acyclic 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 : rituraj_jain