Gráfico de transposición

La transposición de un gráfico dirigido G es otro gráfico dirigido en el mismo conjunto de vértices con todas las aristas invertidas en comparación con la orientación de las aristas correspondientes en G. Es decir, si G contiene una arista (u, v) entonces lo contrario/ la transposición/reversa de G contiene un borde (v, u) y viceversa. Dado un gráfico (representado como una lista de adyacencia) , necesitamos encontrar otro gráfico que sea la transposición del gráfico dado. 

Ejemplo:

Transpose graph

Gráfico de transposición

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

Atravesamos la lista de adyacencia y cuando encontramos un vértice v en la lista de adyacencia del vértice u que indica un borde de u a v en el gráfico principal, simplemente agregamos un borde de v a u en el gráfico de transposición, es decir, agrega u en la adyacencia lista de vértices v del nuevo grafo. Por lo tanto, al atravesar listas de todos los vértices del gráfico principal, podemos obtener el gráfico de transposición. Por tanto, la complejidad temporal total del algoritmo es O(V+E), donde V es el número de vértices del gráfico y E es el número de aristas del gráfico. Nota: es simple obtener la transposición de un gráfico que se almacena en formato de array de adyacencia, solo necesita obtener la transposición de esa array. 

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>
Producción:

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

Publicación traducida automáticamente

Artículo escrito por ab_gupta y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *