Convert the undirected graph into directed graph such that there is no path of length greater than 1

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. Examples:
Input:
Output: 1 2 1 3 1 4
Input:
Output: -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:Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 100005Â
// To store the graphvector<int> gr[N];Â
// To store colour of each vertexint colour[N];Â
// To store edgesvector<pair<int, int> > edges;Â
// To check graph is bipartite or notbool bip;Â
// Function to add edgesvoid add_edge(int x, int y){Â Â Â Â gr[x].push_back(y);Â Â Â Â gr[y].push_back(x);Â Â Â Â edges.push_back(make_pair(x, y));}Â
// Function to check given graph// is bipartite or notvoid dfs(int x, int col){    // colour the vertex x    colour[x] = col;Â
    // For all it's child vertices    for (auto i : gr[x]) {        // If still not visited        if (colour[i] == -1)            dfs(i, col ^ 1);Â
        // If visited and having        // same colour as parent        else if (colour[i] == col)            bip = false;    }}Â
// Function to convert the undirected// graph into the directed graph such that// there is no path of length greater than 1void Directed_Graph(int n, int m){Â
    // Initially each vertex has no colour    memset(colour, -1, sizeof colour);Â
    // Suppose bipartite is possible    bip = true;Â
    // Call bipartite function    dfs(1, 1);Â
    // If bipartite is not possible    if (!bip) {        cout << -1;        return;    }Â
    // If bipartite is possible    for (int i = 0; i < m; i++) {Â
        // Make an edge from vertex having        // colour 1 to colour 0        if (colour[edges[i].first] == 0)            swap(edges[i].first, edges[i].second);Â
        cout << edges[i].first << " "             << edges[i].second << endl;    }}Â
// Driver codeint main(){Â Â Â Â int n = 4, m = 3;Â
    // Add edges    add_edge(1, 2);    add_edge(1, 3);    add_edge(1, 4);Â
    // Function call    Directed_Graph(n, m);Â
    return 0;} |
Java
// Java implementation of the approachimport java.util.*;Â
class GFG{static class pair{ Â Â Â Â int first, second; Â Â Â Â public pair(int first, int second) Â Â Â Â { Â Â Â Â Â Â Â Â this.first = first; Â Â Â Â Â Â Â Â this.second = second; Â Â Â Â } } Â
static int N = 100005;Â
// To store the graphstatic Vector<Integer> []gr = new Vector[N];Â
// To store colour of each vertexstatic int []colour = new int[N];Â
// To store edgesstatic Vector<pair> edges = new Vector<>();Â
// To check graph is bipartite or notstatic boolean bip;Â
// Function to add edgesstatic void add_edge(int x, int y){Â Â Â Â gr[x].add(y);Â Â Â Â gr[y].add(x);Â Â Â Â edges.add(new pair(x, y));}Â
// Function to check given graph// is bipartite or notstatic void dfs(int x, int col){    // colour the vertex x    colour[x] = col;Â
    // For all it's child vertices    for (Integer i : gr[x])    {        // If still not visited        if (colour[i] == -1)            dfs(i, col ^ 1);Â
        // If visited and having        // same colour as parent        else if (colour[i] == col)            bip = false;    }}Â
// Function to convert the undirected// graph into the directed graph such that// there is no path of length greater than 1static void Directed_Graph(int n, int m){Â
    // Initially each vertex has no colour    for (int i = 0; i < N; i++)        colour[i] = -1;Â
    // Suppose bipartite is possible    bip = true;Â
    // Call bipartite function    dfs(1, 1);Â
    // If bipartite is not possible    if (!bip)     {        System.out.print(-1);        return;    }Â
    // If bipartite is possible    for (int i = 0; i < m; i++)     {Â
        // Make an edge from vertex having        // colour 1 to colour 0        if (colour[edges.get(i).first] == 0)        {            Collections.swap(edges, edges.get(i).first,                                     edges.get(i).second);        }Â
        System.out.println(edges.get(i).first + " " +                            edges.get(i).second);    }}Â
// Driver codepublic static void main(String[] args){    int n = 4, m = 3;    for (int i = 0; i < N; i++)        gr[i] = new Vector<>();             // Add edges    add_edge(1, 2);    add_edge(1, 3);    add_edge(1, 4);Â
    // Function call    Directed_Graph(n, m);}}Â
// This code is contributed by PrinciRaj1992 |
Python3
# Python3 implementation of the approachÂ
N = 100005  # To store the graphgr = [[] for i in range(N)]  # To store colour of each vertexcolour = [-1] * N  # To store edgesedges = []  # To check graph is bipartite or notbip = True  # Function to add edgesdef add_edge(x, y):Â
    gr[x].append(y)    gr[y].append(x)    edges.append((x, y))Â
# Function to check given graph# is bipartite or notdef dfs(x, col):Â
    # colour the vertex x    colour[x] = col    global bip      # For all it's child vertices    for i in gr[x]:         # If still not visited        if colour[i] == -1:            dfs(i, col ^ 1)          # If visited and having        # same colour as parent        elif colour[i] == col:            bip = False     # Function to convert the undirected# graph into the directed graph such that# there is no path of length greater than 1def Directed_Graph(n, m):Â
    # Call bipartite function    dfs(1, 1)      # If bipartite is not possible    if not bip:        print(-1)        return         # If bipartite is possible    for i in range(0, m):           # Make an edge from vertex        # having colour 1 to colour 0        if colour[edges[i][0]] == 0:            edges[i][0], edges[i][1] = edges[i][1], edges[i][0]          print(edges[i][0], edges[i][1])  # Driver codeif __name__ == "__main__":Â
    n, m = 4, 3      # Add edges    add_edge(1, 2)    add_edge(1, 3)    add_edge(1, 4)      # Function call    Directed_Graph(n, m)  # This code is contributed by Rituraj Jain |
C#
// C# implementation of the approachusing System;using System.Collections.Generic;Â Â Â Â Â class GFG{Â
class pair{ Â Â Â Â public int first, second; Â Â Â Â public pair(int first, int second) Â Â Â Â { Â Â Â Â Â Â Â Â this.first = first; Â Â Â Â Â Â Â Â this.second = second; Â Â Â Â } } Â
static int N = 100005;Â
// To store the graphstatic List<int> []gr = new List<int>[N];Â
// To store colour of each vertexstatic int []colour = new int[N];Â
// To store edgesstatic List<pair> edges = new List<pair>();Â
// To check graph is bipartite or notstatic Boolean bip;Â
// Function to add edgesstatic void add_edge(int x, int y){Â Â Â Â gr[x].Add(y);Â Â Â Â gr[y].Add(x);Â Â Â Â edges.Add(new pair(x, y));}Â
// Function to check given graph// is bipartite or notstatic void dfs(int x, int col){    // colour the vertex x    colour[x] = col;Â
    // For all it's child vertices    foreach (int i in gr[x])    {        // If still not visited        if (colour[i] == -1)            dfs(i, col ^ 1);Â
        // If visited and having        // same colour as parent        else if (colour[i] == col)            bip = false;    }}Â
// Function to convert the undirected// graph into the directed graph such that// there is no path of length greater than 1static void Directed_Graph(int n, int m){Â
    // Initially each vertex has no colour    for (int i = 0; i < N; i++)        colour[i] = -1;Â
    // Suppose bipartite is possible    bip = true;Â
    // Call bipartite function    dfs(1, 1);Â
    // If bipartite is not possible    if (!bip)     {        Console.Write(-1);        return;    }Â
    // If bipartite is possible    for (int i = 0; i < m; i++)     {Â
        // Make an edge from vertex having        // colour 1 to colour 0        if (colour[edges[i].first] == 0)        {            var v = edges[i].first;            edges[i].first = edges[i].second;            edges[i].second = v;        }Â
        Console.WriteLine(edges[i].first + " " +                           edges[i].second);    }}Â
// Driver codepublic static void Main(String[] args){    int n = 4, m = 3;    for (int i = 0; i < N; i++)        gr[i] = new List<int>();             // Add edges    add_edge(1, 2);    add_edge(1, 3);    add_edge(1, 4);Â
    // Function call    Directed_Graph(n, m);}}Â
// This code is contributed by Rajput-Ji |
Javascript
<script>Â
// JavaScript code to implement the above approach// Python3 implementation of the approachlet N = 100005Â
// To store the graphlet gr = new Array(N);for(let i = 0; i < N; i++){Â Â Â Â gr[i] = new Array()}Â
// To store colour of each vertexlet colour = new Array(N).fill(-1)Â
// To store edgeslet edges = []Â
// To check graph is bipartite or notlet bip = trueÂ
// Function to add edgesfunction add_edge(x, y){Â
    gr[x].push(y)    gr[y].push(x)    edges.push([x, y])}Â
// Function to check given graph// is bipartite or notfunction dfs(x, col){Â
    // colour the vertex x    colour[x] = colÂ
    // For all it's child vertices    for(let i of gr[x]){        // If still not visited        if(colour[i] == -1)            dfs(i, col ^ 1)Â
        // If visited and having        // same colour as parent        else if(colour[i] == col)            bip = false    }}     // Function to convert the undirected// graph into the directed graph such that// there is no path of length greater than 1function Directed_Graph(n, m){Â
    // Call bipartite function    dfs(1, 1)Â
    // If bipartite is not possible    if(bip == 0){        document.write(-1,"</br>")        return    }         // If bipartite is possible    for(let i=0;i<m;i++){Â
        // Make an edge from vertex        // having colour 1 to colour 0        if(colour[edges[i][0]] == 0){            let temp = edges[i][0]            edges[i][0] = edges[i][1]            edges[i][1] = temp        }Â
        document.write(edges[i][0], edges[i][1],"</br>")    }}// Driver codeÂ
let n =4, m = 3Â
// Add edgesadd_edge(1, 2)add_edge(1, 3)add_edge(1, 4)Â
// Function callDirected_Graph(n, m)Â
// This code is contributed by shinjanpatraÂ
</script> |
1 2 1 3 1 4
Time Complexity: O(V + E)
The time complexity of the above approach is O(V + E) where V is the number of vertices and E is the number of edges in the given graph. Since we are traversing the graph using DFS, the time complexity is proportional to the number of vertices plus the number of edges in the graph.
Space Complexity: O(V + E)
The space complexity of the above approach is also O(V + E) as we are using an adjacency list to store the graph and also a vector to store the edges.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Output: 1 2 1 3 1 4 


