Open In App

Transpose graph

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in G. That is, if G contains an edge (u, v) then the converse/transpose/reverse of G contains an edge (v, u) and vice versa. Given a graph (represented as adjacency list), we need to find another graph which is the transpose of the given graph. 

Example:

Transpose-Graph

Input : figure (i) is the input graph.
Output : figure (ii) is the transpose graph of the given graph.

We traverse the adjacency list and as we find a vertex v in the adjacency list of vertex u which indicates an edge from u to v in main graph, we just add an edge from v to u in the transpose graph i.e. add u in the adjacency list of vertex v of the new graph. Thus traversing lists of all vertices of main graph we can get the transpose graph. Thus the total time complexity of the algorithm is O(V+E) where V is number of vertices of graph and E is the number of edges of the graph. Note : It is simple to get the transpose of a graph which is stored in adjacency matrix format, you just need to get the transpose of that matrix. 

Implementation:

C++




// CPP program to find transpose of a graph.
#include <bits/stdc++.h>
using namespace std;
 
// function to add an edge from vertex source to vertex dest
void addEdge(vector<int> adj[], int src, int dest)
{
    adj[src].push_back(dest);
}
 
// function to print adjacency list of a graph
void displayGraph(vector<int> adj[], int v)
{
    for (int i = 0; i < v; i++) {
        cout << i << "--> ";
        for (int j = 0; j < adj[i].size(); j++)
            cout << adj[i][j] << "  ";
        cout << "\n";
    }
}
 
// function to get Transpose of a graph taking adjacency
// list of given graph and that of Transpose graph
void transposeGraph(vector<int> adj[],
                     vector<int> transpose[], int v)
{
    // traverse the adjacency list of given graph and
    // for each edge (u, v) add an edge (v, u) in the
    // transpose graph's adjacency list
    for (int i = 0; i < v; i++)
        for (int j = 0; j < adj[i].size(); j++)
            addEdge(transpose, adj[i][j], i);
}
 
int main()
{
    int v = 5;
    vector<int> adj[v];
    addEdge(adj, 0, 1);
    addEdge(adj, 0, 4);
    addEdge(adj, 0, 3);
    addEdge(adj, 2, 0);
    addEdge(adj, 3, 2);
    addEdge(adj, 4, 1);
    addEdge(adj, 4, 3);
 
    // Finding transpose of graph represented
    // by adjacency list adj[]
    vector<int> transpose[v];
    transposeGraph(adj, transpose, v);
 
    // displaying adjacency list of transpose
    // graph i.e. b
    displayGraph(transpose, v);
 
    return 0;
}


Java




// Java program to find the transpose of a graph
import java.util.*;
import java.lang.*;
import java.io.*;
 
class Graph
{
    // Total number of vertices
    private static int vertices = 5;
     
    // Find transpose of graph represented by adj
    private static ArrayList<Integer>[] adj = new ArrayList[vertices];
    
    // Store the transpose of graph represented by tr
    private static ArrayList<Integer>[] tr = new ArrayList[vertices];
 
    // Function to add an edge from source vertex u to
    // destination vertex v, if choice is false the edge is added
    // to adj otherwise the edge is added to tr
    public static void addedge(int u, int v, boolean choice)
    {
        if(!choice)
            adj[u].add(v);
        else
            tr[u].add(v);
    }
 
    // Function to print the graph representation
    public static void printGraph()
    {
        for(int i = 0; i < vertices; i++)
        {
            System.out.print(i + "--> ");
            for(int j = 0; j < tr[i].size(); j++)
                System.out.print(tr[i].get(j) + " ");
            System.out.println();
        }
    }
 
    // Function to print the transpose of
    // the graph represented as adj and store it in tr
    public static void getTranspose()
    {
 
        // Traverse the graph and for each edge u, v
        // in graph add the edge v, u in transpose
        for(int i = 0; i < vertices; i++)
            for(int j = 0; j < adj[i].size(); j++)
                addedge(adj[i].get(j), i, true);
    }
 
    public static void main (String[] args) throws java.lang.Exception
    {
        for(int i = 0; i < vertices; i++)
        {
            adj[i] = new ArrayList<Integer>();
            tr[i] = new ArrayList<Integer>();
        }
        addedge(0, 1, false);
        addedge(0, 4, false);
        addedge(0, 3, false);
        addedge(2, 0, false);
        addedge(3, 2, false);
        addedge(4, 1, false);
        addedge(4, 3, false);
         
        // Finding transpose of the graph
        getTranspose();
         
        // Printing the graph representation
        printGraph();
    }
}
 
// This code is contributed by code_freak


Python3




# Python3 program to find transpose of a graph.
 
# function to add an edge from vertex
# source to vertex dest
def addEdge(adj, src, dest):
    adj[src].append(dest)
 
# function to print adjacency list
# of a graph
def displayGraph(adj, v):
    for i in range(v):
        print(i, "--> ", end = "")
        for j in range(len(adj[i])):
            print(adj[i][j], end = " ")
        print()
 
# function to get Transpose of a graph
# taking adjacency list of given graph
# and that of Transpose graph
def transposeGraph(adj, transpose, v):
     
    # traverse the adjacency list of given
    # graph and for each edge (u, v) add
    # an edge (v, u) in the transpose graph's
    # adjacency list
    for i in range(v):
        for j in range(len(adj[i])):
            addEdge(transpose, adj[i][j], i)
 
# Driver Code
if __name__ == '__main__':
 
    v = 5
    adj = [[] for i in range(v)]
    addEdge(adj, 0, 1)
    addEdge(adj, 0, 4)
    addEdge(adj, 0, 3)
    addEdge(adj, 2, 0)
    addEdge(adj, 3, 2)
    addEdge(adj, 4, 1)
    addEdge(adj, 4, 3)
 
    # Finding transpose of graph represented
    # by adjacency list adj[]
    transpose = [[]for i in range(v)]
    transposeGraph(adj, transpose, v)
 
    # displaying adjacency list of
    # transpose graph i.e. b
    displayGraph(transpose, v)
 
# This code is contributed by PranchalK


C#




// C# program to find the transpose of a graph
using System;
using System.Collections.Generic;
 
class Graph
{
    // Total number of vertices
    private static int vertices = 5;
     
    // Find transpose of graph represented by adj
    private static List<int>[] adj = new List<int>[vertices];
     
    // Store the transpose of graph represented by tr
    private static List<int>[] tr = new List<int>[vertices];
 
    // Function to add an edge from source vertex u to
    // destination vertex v, if choice is false the edge is added
    // to adj otherwise the edge is added to tr
    public static void addedge(int u, int v, bool choice)
    {
        if(!choice)
            adj[u].Add(v);
        else
            tr[u].Add(v);
    }
 
    // Function to print the graph representation
    public static void printGraph()
    {
        for(int i = 0; i < vertices; i++)
        {
            Console.Write(i + "--> ");
            for(int j = 0; j < tr[i].Count; j++)
                Console.Write(tr[i][j] + " ");
            Console.WriteLine();
        }
    }
 
    // Function to print the transpose of
    // the graph represented as adj and store it in tr
    public static void getTranspose()
    {
 
        // Traverse the graph and for each edge u, v
        // in graph add the edge v, u in transpose
        for(int i = 0; i < vertices; i++)
            for(int j = 0; j < adj[i].Count; j++)
                addedge(adj[i][j], i, true);
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        for(int i = 0; i < vertices; i++)
        {
            adj[i] = new List<int>();
            tr[i] = new List<int>();
        }
        addedge(0, 1, false);
        addedge(0, 4, false);
        addedge(0, 3, false);
        addedge(2, 0, false);
        addedge(3, 2, false);
        addedge(4, 1, false);
        addedge(4, 3, false);
         
        // Finding transpose of the graph
        getTranspose();
         
        // Printing the graph representation
        printGraph();
    }
}
 
 
// This code is contributed by Rajput-Ji


Javascript




<script>
// Javascript program to find transpose of a graph.
 
// function to add an edge from vertex
// source to vertex dest
function addEdge(adj, src, dest) {
  adj[src].push(dest)
}
 
// function to print adjacency list
// of a graph
function displayGraph(adj, v) {
  for (let i = 0; i < v; i++) {
    document.write(i + "--> ")
    for (let j = 0; j < adj[i].length; j++) {
      document.write(adj[i][j] + " ")
    }
    document.write("<br>")
  }
}
 
// function to get Transpose of a graph
// taking adjacency list of given graph
// and that of Transpose graph
function transposeGraph(adj, transpose, v) {
 
  // traverse the adjacency list of given
  // graph and for each edge (u, v) add
  // an edge (v, u) in the transpose graph's
  // adjacency list
  for (let i = 0; i < v; i++)
    for (let j = 0; j < adj[i].length; j++)
      addEdge(transpose, adj[i][j], i)
}
 
// Driver Code
let v = 5
let adj = new Array(v).fill(0).map(() => new Array())
addEdge(adj, 0, 1)
addEdge(adj, 0, 4)
addEdge(adj, 0, 3)
addEdge(adj, 2, 0)
addEdge(adj, 3, 2)
addEdge(adj, 4, 1)
addEdge(adj, 4, 3)
 
// Finding transpose of graph represented
// by adjacency list adj[]
let transpose = new Array(v).fill(0).map(() => new Array())
transposeGraph(adj, transpose, v)
 
// displaying adjacency list of
// transpose graph i.e. b
displayGraph(transpose, v)
 
// This code is contributed by Saurabh Jaiswal
 
</script>


Output

0--> 2  
1--> 0  4  
2--> 3  
3--> 0  4  
4--> 0  

Time Complexity:

The time complexity of the addEdge function is O(1), as it simply appends an element to the vector.

The time complexity of the displayGraph function is O(V + E), where V is the number of vertices and E is the number of edges, as it needs to traverse the adjacency list of each vertex and print out the adjacent vertices.

The time complexity of the transposeGraph function is also O(V + E), where V is the number of vertices and E is the number of edges, as it needs to traverse the adjacency list of each vertex and add the corresponding edges to the transpose graph’s adjacency list.

Therefore, the overall time complexity of the program is O(V + E).

Space complexity:

In terms of space complexity, the program uses two arrays of vectors to represent the original graph and its transpose, each of which has a size of V (the number of vertices). Additionally, the program uses a constant amount of space to store integer variables and temporary data structures. Therefore, the space complexity of the program is O(V).

Note that the space complexity of the program could be larger if the input graph has a large number of edges, as this would require more memory to store the adjacency lists.



Previous Article
Next Article

Similar Reads

Inplace (Fixed space) M x N size matrix transpose
Given an M x N matrix, transpose the matrix without auxiliary memory.It is easy to transpose matrix using an auxiliary array. If the matrix is symmetric in size, we can transpose the matrix inplace by mirroring the 2D array across it's diagonal (try yourself). How to transpose an arbitrary size matrix inplace? See the following matrix, a b c a d g
15+ min read
Python Program to find transpose of a matrix
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]. For Square Matrix: The below program finds transpose of A[][] and stores the result in B[][], we can change N for different dimension. C/C++ Code # Python3 Program to find # transpose of a
5 min read
Program to find transpose of a matrix
Given a matrix of size N X M, find the transpose of the matrixTranspose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[N][M] is obtained by changing A[i][j] to A[j][i]. Example: Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. Approach: Follow the given ste
10 min read
C++ Program To Find Transpose of a Matrix
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, the transpose of A[][] is obtained by changing A[i][j] to A[j][i]. Example: Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. 1. For Square Matrix The below program finds the transpose of A[][] and stores the result
4 min read
Detect cycle in the graph using degrees of nodes of graph
Given a graph, the task is to detect a cycle in the graph using degrees of the nodes in the graph and print all the nodes that are involved in any of the cycles. If there is no cycle in the graph then print -1. Examples: Input: Output: 0 1 2 Approach: Recursively remove all vertices of degree 1. This can be done efficiently by storing a map of vert
11 min read
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 destin
10 min read
Maximum number of edges that N-vertex graph can have such that graph is Triangle free | Mantel's Theorem
Given a number N which is the number of nodes in a graph, the task is to find the maximum number of edges that N-vertex graph can have such that graph is triangle-free (which means there should not be any three edges A, B, C in the graph such that A is connected to B, B is connected to C and C is connected to A). The graph cannot contain a self-loo
4 min read
Convert undirected connected graph to strongly connected directed graph
Given an undirected graph of N vertices and M edges, the task is to assign directions to the given M Edges such that the graph becomes Strongly Connected Components. If a graph cannot be converted into Strongly Connected Components then print "-1". Examples: Input: N = 5, Edges[][] = { { 0, 1 }, { 0, 2 }, { 1, 2 }, { 1, 4 }, { 2, 3 }, { 3, 4 } } Ou
14 min read
Java Program to Find Independent Sets in a Graph using Graph Coloring
Independent sets are set of vertices or edges in which the pair of any two vertices or edges are not adjacent to each other. Assuming that Independent sets mean Independent sets of vertices, we have to find a set of such vertices in which any two pairs of the vertex are not adjacent to each other. Using graph coloring we can solve this problem. We
13 min read
Connect a graph by M edges such that the graph does not contain any cycle and Bitwise AND of connected vertices is maximum
Given an array arr[] consisting of values of N vertices of an initially unconnected Graph and an integer M, the task is to connect some vertices of the graph with exactly M edges, forming only one connected component, such that no cycle can be formed and Bitwise AND of the connected vertices is maximum possible. Examples: Input: arr[] = {1, 2, 3, 4
9 min read
Article Tags :
Practice Tags :