Print adjacency list of a Bidirectional Graph Last Updated : 07 Dec, 2022 Summarize Comments Improve Suggest changes Share Like Article Like 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 = 5adj[] = adj[0] = {1, 2}; adj[2] = {0, 3, 4}; adj[3] = {1, 2}; adj[4] = {2}; Output: Node 0 is connected to 1 and 2Node 1 is connected to 0 and 3Node 2 is connected to 0,3 and 4Node 3 is connected to 1 and 2Node 4 is connected to 2 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 OutputNode 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 graphAuxiliary Space: O ( V + E ) Related Articles: Introduction to Graphs – Data Structure and Algorithm TutorialsGraph and its representations Comment More infoAdvertise with us Next Article Print adjacency list of a Bidirectional Graph S sarkarrohit650 Follow Improve Article Tags : Graph Technical Scripter DSA Technical Scripter 2022 Practice Tags : Graph Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous 4 min read Like