Open In App

Print adjacency list of a Bidirectional Graph

Last Updated : 07 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given the adjacency list of a bidirectional graph. The task is to copy/clone the adjacency list for each vertex and return a new list for a bidirectional graph.

An Adjacency List is used for representing graphs. Here, for every vertex in the graph, we have a list of all the other vertices to which the particular vertex has an edge.

Examples:

Input: N = 5
adj[] = adj[0] = {1, 2}; adj[2] = {0, 3, 4}; adj[3] = {1, 2}; adj[4] = {2};

Output: Node 0 is connected to 1 and 2
Node 1 is connected to 0 and 3
Node 2 is connected to 0,3 and 4
Node 3 is connected to 1 and 2
Node 4 is connected to 2

The example graph

The example graph

Approach:

The basic Idea to clone adjacency list for each vertex is to create a cloned vector and a visited array and check whether the node is visited or not.

  • First Create a vector (say clone) of size N and an array visited[] of size N to check whether a particular is visited or not.
  • Check if a node is visited or not: 
    • If not, then call a function to mark a non-visited node as present
  •  Create two vectors adj[] and clone[] where adj[] has a list stored in it and clone[] will store the unmarked nodes.
  • Mark every node as visited by visited[node] = 1.
  • Then, traverse the adjacency list and check for non-visited nodes to add edges in the bidirectional graph.
    • Push nodes and edges in the clone list

Below is the implementation of the above idea:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to add the edges we have
// in the adjacency list to the clone list
void AddEdges(int node, vector<int> adj[],
              vector<int> clone[], vector<int>& visited)
{
    // Marking node as visited
    visited[node] = 1;
 
    for (int it : adj[node]) {
        if (!visited[it]) {
 
            // Nodes are bidirectionally connected
            clone[node].push_back(it);
            clone[it].push_back(node);
        }
    }
}
 
// Function to print the adjacency list
void printList(vector<int> clone[], int n)
{
    for (int node = 0; node < n; node++) {
        cout << "Node " << node << " is connected to ";
        for (int it : clone[node]) {
            cout << it << " ";
        }
        cout << endl;
    }
}
 
// Function to clone the given adjacency list
void cloneList(vector<int> adj[], int N)
{
    vector<int> clone[N];
 
    // Visited array to check whether a particular
    // node is visited or not
    vector<int> visited(N, 0);
 
    for (int node = 0; node < N; node++) {
        if (!visited[node]) {
            AddEdges(node, adj, clone, visited);
        }
    }   
    printList(clone, N);
}
 
// Driver code
int main()
{
    // Adjacency List of a bidirectional graph
    int N = 5;
    vector<int> adj[N];
    adj[0] = { 1, 2 };
    adj[1] = { 0, 3 };
    adj[2] = { 0, 3, 4 };
    adj[3] = { 1, 2 };
    adj[4] = { 2 };
 
    // Function call
    cloneList(adj, N);
 
    return 0;
}


Java




// Java code to implement the approach
 
import java.util.*;
 
class GFG {
 
    // Function to add the edges we have
    // in the adjacency list to the clone list
    public static void AddEdges(int node,
                                ArrayList<Integer>[] adj,
                                ArrayList<Integer>[] clone,
                                boolean[] visited)
    {
        visited[node] = true;
 
        for (int it : adj[node]) {
            if (!visited[it]) {
                clone[node].add(it);
                clone[it].add(node);
            }
        }
    }
 
    // Function to clone the given adjacency list
    static void cloneList(ArrayList<Integer> adj[], int n)
    {
        ArrayList<Integer>[] clone = new ArrayList[n];
        for (int i = 0; i < n; i++)
            clone[i] = new ArrayList<>();
 
        // Visited array to check
        // whether a particular node is
        // visited or not
        boolean[] visited = new boolean[n];
 
        for (int node = 0; node < n; node++) {
            if (!visited[node]) {
                AddEdges(node, adj, clone, visited);
            }
        }
       
        // Printing cloned the adjacency list
        for (int node = 0; node < n; node++) {
            System.out.print("Node " + node
                             + " is connected to ");
            for (int it : clone[node]) {
                System.out.print(it + " ");
            }
            System.out.println();
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Adjacency List of a bidirectional graph
        int N = 5;
        ArrayList<Integer>[] adj = new ArrayList[N];
 
        adj[0] = new ArrayList<>(List.of(1, 2));
        adj[1] = new ArrayList<>(List.of(0, 3));
        adj[2] = new ArrayList<>(List.of(0, 3, 4));
        adj[3] = new ArrayList<>(List.of(1, 2));
        adj[4] = new ArrayList<>(List.of(2));
       
        cloneList(adj, N); 
    }
}


Python3




# Python code to implement the approach
 
# Function to add the edges we have
# in the adjacency list to the clone list
def AddEdges(node, adj, clone, visited):
    # Marking node as visited
    visited[node] = 1
     
    for i in range(len(adj[node])):
        it=adj[node][i]
        if(not visited[it]):
            # Nodes are bidirectionally connected
            clone[node].append(it)
            clone[it].append(node)
     
# Function to print the adjacency list
def printList(clone,n):
    for node in range(n):
        print("Node ",end="")
        print(node,end="")
        print(" is connected to ",end="")
        for it in clone[node]:
            print(it,end=" ")
        print()
     
# Function to clone the given adjacency list
def cloneList(adj,N):
    clone=[[] for j in range(N)]
     
    # Visited array to check whether a particular
    # node is visited or not
    visited=[0]*N
     
    for node in range(N):
        if(not visited[node]):
            AddEdges(node, adj, clone, visited)
             
    printList(clone, N)
     
# Driver code
 
# Adjacency List of a bidirectional graph
N = 5
adj = [[] for j in range(N)]
adj[0] = [1, 2]
adj[1] = [0, 3]
adj[2] = [0, 3, 4]
adj[3] = [1, 2]
adj[4] = [2]
 
# Function call
cloneList(adj, N)
 
# This code is contributed by Pushpesh Raj.


C#




using System;
 
public class GFG{
 
    static public void Main (){
 
        // Code
    }


Javascript




// JS code to implement the approach
 
// Function to add the edges we have
// in the adjacency list to the clone list
function AddEdges(node, adj, clone, visited)
{
    // Marking node as visited
    visited[node] = 1;
 
    for(let i=0;i<adj[node].length;i++){
        let it = adj[node][i];
        if (!visited[it]) {
 
            // Nodes are bidirectionally connected
            clone[node].push(it);
            clone[it].push(node);
        }
    }
}
 
// Function to print the adjacency list
function printList( clone, n)
{
    for (let node = 0; node < n; node++) {
        console.log( "Node " , node , " is connected to ", clone[node]);
    }
}
 
// Function to clone the given adjacency list
function cloneList(adj, N)
{
    let clone  = [];
    for(let i = 0; i < N; i++)
    {
        clone.push([]);
    }
 
    // Visited array to check whether a particular
    // node is visited or not
    let visited = [];
    for(let i = 0; i < N; i++)
    {
        visited.push(0);
    }
 
    for (let node = 0; node < N; node++) {
        if (!visited[node]) {
            AddEdges(node, adj, clone, visited);
        }
    }   
    printList(clone, N);
}
 
// Driver code
// Adjacency List of a bidirectional graph
let N = 5;
let adj = [];
for(let i =0;i<N;i++)
{
    adj.push([]);
}
adj[0] = [ 1, 2 ];
adj[1] = [ 0, 3 ];
adj[2] = [ 0, 3, 4 ];
adj[3] = [ 1, 2 ];
adj[4] = [ 2 ];
 
// Function call
cloneList(adj, N);
 
// This code is contributed by ksam24000


Output

Node 0 is connected to 1 2 
Node 1 is connected to 0 3 
Node 2 is connected to 0 3 4 
Node 3 is connected to 1 2 
Node 4 is connected to 2 

Time Complexity: O ( V + E ) where V is the number of vertices and E is the number of edges of the graph
Auxiliary Space: O ( V + E )

Related Articles:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads