Given an undirected graph with multiple connected components, the task is to clone the graph. Cloning a graph with a single connected component can be seen here.
Examples:
An example of an undirected graph with 3 connected components:
Approach: The idea is to follow the same approach posted for cloning connected graph, but with every node so that we can clone graphs with multiple connected components.
We are going to use a GraphNode class and a Graph class. The Graph class is compulsory, since we might have multiple connected components (see example above), and we cannot deal with them having only a GraphNode as an input. For the Graph class, what we actually need is a list of GraphNodes. It’s also possible to make a list of nodes instead of creating a class, both ways work.
To keep track of the visited nodes, we need a data structure; a map is an appropriate one, as we can map from the “old” nodes to the “new” ones (the cloned). So, we are defining a main function, which creates the map, and uses a helper function to fill it. Once the map is created, a new graph can be created, using the cloned nodes in the map.
The helper function is going to put connections between nodes (besides filling the map). As we are dealing with a whole connected component, a similar approach to the BFS is going to be followed.
Notice that in the main function, we don’t call the helper function for each node in the Graph; if the node is stored in the map, it means that we’ve already visited it and dealt with its connected component, so no need to repeat the steps again.
In order to check if the graph has been correctly cloned, we can print the memory addresses of the nodes, and compare them to see whether we’ve cloned, or we’ve copied them.
Below is the implementation of the above approach:
C++14
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // GraphNode class represents each // Node of the Graph class GraphNode { int data; list<GraphNode*> children; // Constructor to initialize the // node with value public : GraphNode( int data) { this ->data = data; } // Function to add a child to the // current node void addChild(GraphNode* node) { this ->children.push_back(node); } // Function to return a list of children // for the current node list<GraphNode*> getChildren() { return children; } // Function to set the node's value void setData( int data) { this ->data = data; } // Function to return the node's value int getData() { return data; } }; // Class to represent the graph class Graph { list<GraphNode*> nodes; public : Graph() {} // Constructor to set the graph's nodes Graph(list<GraphNode*> nodes) { this ->nodes = nodes; } // Function to add a node to the graph void addNode(GraphNode* node) { this ->nodes.push_back(node); } // Function to return the list of nodes // for the graph list<GraphNode*> getNodes() { return this ->nodes; } }; class GFG { // Function to clone the graph // Function to clone the connected components void cloneConnectedComponent( GraphNode* node, map<GraphNode*, GraphNode*>& map) { queue<GraphNode*> queue; queue.push(node); while (!queue.empty()) { GraphNode* current = queue.front(); queue.pop(); GraphNode* currentCloned = NULL; if (map.find(current) != map.end()) { currentCloned = map[current]; } else { currentCloned = new GraphNode(current->getData()); map[current] = currentCloned; } list<GraphNode*> children = current->getChildren(); for ( auto child : children) { if (map.find(child) != map.end()) { currentCloned->addChild(map[child]); } else { GraphNode* childCloned = new GraphNode(child->getData()); map[child] = childCloned; currentCloned->addChild(childCloned); queue.push(child); } } } } public : Graph* cloneGraph(Graph* graph) { map<GraphNode*, GraphNode*> mapp; for ( auto node : graph->getNodes()) { if (mapp.find(node) == mapp.end()) cloneConnectedComponent(node, mapp); } Graph* cloned = new Graph(); for ( auto current : mapp) cloned->addNode(current.second); return cloned; } // Function to build the graph Graph* buildGraph() { // Create graph Graph* g = new Graph(); // Adding nodes to the graph GraphNode* g1 = new GraphNode(1); g->addNode(g1); GraphNode* g2 = new GraphNode(2); g->addNode(g2); GraphNode* g3 = new GraphNode(3); g->addNode(g3); GraphNode* g4 = new GraphNode(4); g->addNode(g4); GraphNode* g5 = new GraphNode(5); g->addNode(g5); GraphNode* g6 = new GraphNode(6); g->addNode(g6); // Adding edges g1->addChild(g2); g1->addChild(g3); g2->addChild(g1); g2->addChild(g4); g3->addChild(g1); g3->addChild(g4); g4->addChild(g2); g4->addChild(g3); g5->addChild(g6); g6->addChild(g5); return g; } // Function to print the connected components void printConnectedComponent(GraphNode* node, set<GraphNode*>& visited) { if (visited.find(node) != visited.end()) return ; queue<GraphNode*> q; q.push(node); while (!q.empty()) { GraphNode* currentNode = q.front(); q.pop(); if (visited.find(currentNode) != visited.end()) continue ; visited.insert(currentNode); cout << "Node " << currentNode->getData() << " - " << currentNode << endl; for (GraphNode* child : currentNode->getChildren()) { cout << "\tNode " << child->getData() << " - " << child << endl; q.push(child); } } } }; // Driver code int main() { GFG* gfg = new GFG(); Graph* g = gfg->buildGraph(); // Original graph cout << "\tINITIAL GRAPH\n" ; set<GraphNode*> visited; for (GraphNode* n : g->getNodes()) gfg->printConnectedComponent(n, visited); // Cloned graph cout << "\n\n\tCLONED GRAPH\n" ; Graph* cloned = gfg->cloneGraph(g); visited.clear(); for (GraphNode* node : cloned->getNodes()) gfg->printConnectedComponent(node, visited); } // This code is contributed by sanjeev2552 |
Java
// Java implementation of the approach import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; // Class to represent the graph class Graph { private List<GraphNode> nodes; // Constructor to create an empty ArrayList // to store the nodes of the graph public Graph() { this .nodes = new ArrayList<GraphNode>(); } // Constructor to set the graph's nodes public Graph(List<GraphNode> nodes) { this .nodes = nodes; this .nodes = new ArrayList<GraphNode>(); } // Function to add a node to the graph public void addNode(GraphNode node) { this .nodes.add(node); } // Function to return the list of nodes // for the graph public List<GraphNode> getNodes() { return this .nodes; } } // GraphNode class represents each // Node of the Graph class GraphNode { private int data; private List<GraphNode> children; // Constructor to initialize the node with value public GraphNode( int data) { this .data = data; this .children = new ArrayList<GraphNode>(); } // Function to add a child to the current node public void addChild(GraphNode node) { this .children.add(node); } // Function to return a list of children // for the current node public List<GraphNode> getChildren() { return children; } // Function to set the node's value public void setData( int data) { this .data = data; } // Function to return the node's value public int getData() { return data; } } public class GFG { // Function to clone the graph public Graph cloneGraph(Graph graph) { Map<GraphNode, GraphNode> map = new HashMap<GraphNode, GraphNode>(); for (GraphNode node : graph.getNodes()) { if (!map.containsKey(node)) cloneConnectedComponent(node, map); } Graph cloned = new Graph(); for (GraphNode current : map.values()) cloned.addNode(current); return cloned; } // Function to clone the connected components private void cloneConnectedComponent(GraphNode node, Map<GraphNode, GraphNode> map) { Queue<GraphNode> queue = new LinkedList<GraphNode>(); queue.add(node); while (!queue.isEmpty()) { GraphNode current = queue.poll(); GraphNode currentCloned = null ; if (map.containsKey(current)) { currentCloned = map.get(current); } else { currentCloned = new GraphNode(current.getData()); map.put(current, currentCloned); } List<GraphNode> children = current.getChildren(); for (GraphNode child : children) { if (map.containsKey(child)) { currentCloned.addChild(map.get(child)); } else { GraphNode childCloned = new GraphNode(child.getData()); map.put(child, childCloned); currentCloned.addChild(childCloned); queue.add(child); } } } } // Function to build the graph public Graph buildGraph() { // Create graph Graph g = new Graph(); // Adding nodes to the graph GraphNode g1 = new GraphNode( 1 ); g.addNode(g1); GraphNode g2 = new GraphNode( 2 ); g.addNode(g2); GraphNode g3 = new GraphNode( 3 ); g.addNode(g3); GraphNode g4 = new GraphNode( 4 ); g.addNode(g4); GraphNode g5 = new GraphNode( 5 ); g.addNode(g5); GraphNode g6 = new GraphNode( 6 ); g.addNode(g6); // Adding edges g1.addChild(g2); g1.addChild(g3); g2.addChild(g1); g2.addChild(g4); g3.addChild(g1); g3.addChild(g4); g4.addChild(g2); g4.addChild(g3); g5.addChild(g6); g6.addChild(g5); return g; } // Function to print the connected components public void printConnectedComponent(GraphNode node, Set<GraphNode> visited) { if (visited.contains(node)) return ; Queue<GraphNode> q = new LinkedList<GraphNode>(); q.add(node); while (!q.isEmpty()) { GraphNode currentNode = q.remove(); if (visited.contains(currentNode)) continue ; visited.add(currentNode); System.out.println( "Node " + currentNode.getData() + " - " + currentNode); for (GraphNode child : currentNode.getChildren()) { System.out.println( "\tNode " + child.getData() + " - " + child); q.add(child); } } } // Driver code public static void main(String[] args) { GFG gfg = new GFG(); Graph g = gfg.buildGraph(); // Original graph System.out.println( "\tINITIAL GRAPH" ); Set<GraphNode> visited = new HashSet<GraphNode>(); for (GraphNode n : g.getNodes()) gfg.printConnectedComponent(n, visited); // Cloned graph System.out.println( "\n\n\tCLONED GRAPH\n" ); Graph cloned = gfg.cloneGraph(g); visited = new HashSet<GraphNode>(); for (GraphNode node : cloned.getNodes()) gfg.printConnectedComponent(node, visited); } } |
Python3
# Python3 implementation of the approach from collections import deque as dq # GraphNode class represents each # Node of the Graph class GraphNode: # Constructor to initialize the # node with value def __init__( self , data): self .__data = data self .__children = [] # Function to add a child to the # current node def addChild( self , node): self .__children.append(node) # Function to return a list of children # for the current node def getChildren( self ): return self .__children # Function to set the node's value def setData( self , data): self .__data = data # Function to return the node's value def getData( self ): return self .__data # Class to represent the graph class Graph: # Constructor to set the graph's nodes def __init__( self , nodes): self .__nodes = nodes # Function to add a node to the graph def addNode( self , node): self .__nodes.append(node) # Function to return the list of nodes # for the graph def getNodes( self ): return self .__nodes class GFG: # Function to clone the connected components def cloneConnectedComponent( self , node, mp): queue = dq([node, ]) while (queue): current = queue.popleft() currentCloned = None if (current in mp): currentCloned = mp[current] else : currentCloned = GraphNode(current.getData()) mp[current] = currentCloned children = current.getChildren() for child in children: if (child in mp): currentCloned.addChild(mp[child]) else : childCloned = GraphNode(child.getData()) mp[child] = childCloned currentCloned.addChild(childCloned) queue.append(child) # Function to clone the graph def cloneGraph( self , graph): mapp = dict () for node in graph.getNodes(): if (node not in mapp): self .cloneConnectedComponent(node, mapp) cloned = Graph([]) for current in mapp: cloned.addNode(mapp[current]) return cloned # Function to build the graph def buildGraph( self ): # Create graph G = Graph([]) # Adding nodes to the graph g1 = GraphNode( 1 ) G.addNode(g1) g2 = GraphNode( 2 ) G.addNode(g2) g3 = GraphNode( 3 ) G.addNode(g3) g4 = GraphNode( 4 ) G.addNode(g4) g5 = GraphNode( 5 ) G.addNode(g5) g6 = GraphNode( 6 ) G.addNode(g6) # Adding edges g1.addChild(g2) g1.addChild(g3) g2.addChild(g1) g2.addChild(g4) g3.addChild(g1) g3.addChild(g4) g4.addChild(g2) g4.addChild(g3) g5.addChild(g6) g6.addChild(g5) return G # Function to print the connected components def printConnectedComponent( self , node, visited): if (node in visited): return q = dq([node, ]) while (q): currentNode = q.popleft() if (currentNode in visited): continue visited.add(currentNode) print ( "Node {} - {}" . format (currentNode.getData(), hex ( id (currentNode)))) for child in currentNode.getChildren(): print ( "\tNode {} - {}" . format (child.getData(), hex ( id (child)))) q.append(child) # Driver code if __name__ = = '__main__' : gfg = GFG() g = gfg.buildGraph() # Original graph print ( "\tINITIAL GRAPH" ) visited = set () for n in g.getNodes(): gfg.printConnectedComponent(n, visited) # Cloned graph print ( "\n\n\tCLONED GRAPH" ) cloned = gfg.cloneGraph(g) visited.clear() for node in cloned.getNodes(): gfg.printConnectedComponent(node, visited) # This code is contributed by Amartya Ghosh |
C#
// C# implementation of the approach using System; using System.Collections.Generic; // Class to represent the graph public class Graph { public List<GraphNode> nodes; // Constructor to create an empty // ArrayList to store the nodes of the graph public Graph() { this .nodes = new List<GraphNode>(); } // Constructor to set the graph's nodes public Graph(List<GraphNode> nodes) { this .nodes = nodes; this .nodes = new List<GraphNode>(); } // Function to add a node to the graph public void addNode(GraphNode node) { this .nodes.Add(node); } // Function to return the list of // nodes for the graph public List<GraphNode> getNodes() { return this .nodes; } } // GraphNode class represents each // Node of the Graph public class GraphNode { public int data; public List<GraphNode> children; // Constructor to initialize the node // with value public GraphNode( int data) { this .data = data; this .children = new List<GraphNode>(); } // Function to add a child to the // current node public void addChild(GraphNode node) { this .children.Add(node); } // Function to return a list of // children for the current node public List<GraphNode> getChildren() { return this .children; } // Function to set the node's value public void setData( int data) { this .data = data; } // Function to return the node's value public int getData() { return this .data; } } public class GFG { // Function to clone the graph public Graph cloneGraph(Graph graph) { Dictionary<GraphNode, GraphNode> map = new Dictionary<GraphNode, GraphNode>(); foreach (GraphNode node in graph.getNodes()) { if (!map.ContainsKey(node)) cloneConnectedComponent(node, map); } Graph cloned = new Graph(); foreach (GraphNode current in map.Values) cloned.addNode(current); return cloned; } // Function to clone the connected // components private void cloneConnectedComponent( GraphNode node, Dictionary<GraphNode, GraphNode> map) { Queue<GraphNode> queue = new Queue<GraphNode>(); queue.Enqueue(node); while (queue.Count != 0) { GraphNode current = queue.Dequeue(); GraphNode currentCloned = null ; if (map.ContainsKey(current)) { currentCloned = map[current]; } else { currentCloned = new GraphNode(current.getData()); map.Add(current, currentCloned); } List<GraphNode> children = current.getChildren(); foreach (GraphNode child in children) { if (map.ContainsKey(child)) { currentCloned.addChild(map[child]); } else { GraphNode childCloned = new GraphNode(child.getData()); map.Add(child, childCloned); currentCloned.addChild(childCloned); queue.Enqueue(child); } } } } // Function to build the graph public Graph buildGraph() { // Create graph Graph g = new Graph(); // Adding nodes to the graph GraphNode g1 = new GraphNode(1); g.addNode(g1); GraphNode g2 = new GraphNode(2); g.addNode(g2); GraphNode g3 = new GraphNode(3); g.addNode(g3); GraphNode g4 = new GraphNode(4); g.addNode(g4); GraphNode g5 = new GraphNode(5); g.addNode(g5); GraphNode g6 = new GraphNode(6); g.addNode(g6); // Adding edges g1.addChild(g2); g1.addChild(g3); g2.addChild(g1); g2.addChild(g4); g3.addChild(g1); g3.addChild(g4); g4.addChild(g2); g4.addChild(g3); g5.addChild(g6); g6.addChild(g5); return g; } // Function to print the connected components public void printConnectedComponent(GraphNode node, HashSet<GraphNode> visited) { if (visited.Contains(node)) return ; Queue<GraphNode> q = new Queue<GraphNode>(); q.Enqueue(node); while (q.Count != 0) { GraphNode currentNode = q.Dequeue(); if (visited.Contains(currentNode)) continue ; visited.Add(currentNode); Console.WriteLine( "Node " + currentNode.getData() + " - " + currentNode); foreach (GraphNode child in currentNode.getChildren()) { Console.WriteLine( "\tNode " + child.getData() + " - " + child); q.Enqueue(child); } } } // Driver code public static void Main( string [] args) { GFG gfg = new GFG(); Graph g = gfg.buildGraph(); // Original graph Console.WriteLine( "\tINITIAL GRAPH" ); HashSet<GraphNode> visited = new HashSet<GraphNode>(); foreach (GraphNode n in g.getNodes()) gfg.printConnectedComponent(n, visited); // Cloned graph Console.WriteLine( "\n\n\tCLONED GRAPH\n" ); Graph cloned = gfg.cloneGraph(g); visited = new HashSet<GraphNode>(); foreach (GraphNode node in cloned.getNodes()) gfg.printConnectedComponent(node, visited); } } |
Javascript
// Class to represent the graph class Graph { constructor() { this .nodes = []; // An array to store the nodes of the graph } // Function to add a node to the graph addNode(node) { this .nodes.push(node); } // Function to return the list of nodes for the graph getNodes() { return this .nodes; } } // GraphNode class represents each Node of the Graph class GraphNode { constructor(data) { this .data = data; // Initialize the node with value this .children = []; // An array to store the children of the node } // Function to add a child to the current node addChild(node) { this .children.push(node); } // Function to return a list of children // for the current node getChildren() { return this .children; } // Function to set the node's value setData(data) { this .data = data; } // Function to return the node's value getData() { return this .data; } } class GFG { // Function to clone the graph cloneGraph(graph) { const map = new Map(); for (const node of graph.getNodes()) { if (!map.has(node)) { this .cloneConnectedComponent(node, map); } } const cloned = new Graph(); for (const node of map.values()) { cloned.addNode(node); } return cloned; } // Function to clone the connected components cloneConnectedComponent(node, map) { const queue = []; queue.push(node); while (queue.length > 0) { const current = queue.shift(); let currentCloned = null ; if (map.has(current)) { currentCloned = map.get(current); } else { currentCloned = new GraphNode(current.getData()); map.set(current, currentCloned); } const children = current.getChildren(); for (const child of children) { if (map.has(child)) { currentCloned.addChild(map.get(child)); } else { const childCloned = new GraphNode(child.getData()); map.set(child, childCloned); currentCloned.addChild(childCloned); queue.push(child); } } } } // Function to build the graph buildGraph() { // Create graph const g = new Graph(); // Adding nodes to the graph const g1 = new GraphNode(1); g.addNode(g1); const g2 = new GraphNode(2); g.addNode(g2); const g3 = new GraphNode(3); g.addNode(g3); const g4 = new GraphNode(4); g.addNode(g4); const g5 = new GraphNode(5); g.addNode(g5); const g6 = new GraphNode(6); g.addNode(g6); g1.addChild(g2); g1.addChild(g3); g2.addChild(g1); g2.addChild(g4); g3.addChild(g1); g3.addChild(g4); g4.addChild(g2); g4.addChild(g3); g5.addChild(g6); g6.addChild(g5); return g; } // Function to print the connected components printConnectedComponent(node, visited) { if (visited.has(node)) { return ; } const q = []; q.push(node); while (q.length > 0) { const currentNode = q.shift(); if (visited.has(currentNode)) { continue ; } visited.add(currentNode); console.log(`Node ${currentNode.getData()} - ${currentNode}`); for (const child of currentNode.getChildren()) { console.log(`\tNode ${child.getData()} - ${child}`); q.push(child); } } } } // Driver Code const gfg = new GFG(); const g = gfg.buildGraph(); // Original graph console.log( "\tINITIAL GRAPH" ); const visited = new Set(); for (const n of g.getNodes()) { gfg.printConnectedComponent(n, visited); } // Cloned graph console.log( "\n\n\tCLONED GRAPH" ); const cloned = gfg.cloneGraph(g); visited.clear(); for (const n of cloned.getNodes()) gfg.printConnectedComponent(n, visited); |
INITIAL GRAPH Node 1 - 0x1104050 Node 2 - 0x1104090 Node 3 - 0x11040d0 Node 2 - 0x1104090 Node 1 - 0x1104050 Node 4 - 0x1104110 Node 3 - 0x11040d0 Node 1 - 0x1104050 Node 4 - 0x1104110 Node 4 - 0x1104110 Node 2 - 0x1104090 Node 3 - 0x11040d0 Node 5 - 0x1104150 Node 6 - 0x1104190 Node 6 - 0x1104190 Node 5 - 0x1104150 CLONED GRAPH Node 1 - 0x1104780 Node 2 - 0x1104850 Node 3 - 0x11048d0 Node 2 - 0x1104850 Node 1 - 0x1104780 Node 4 - 0x1104970 Node 3 - 0x11048d0 Node 1 - 0x1104780 Node 4 - 0x1104970 Node 4 - 0x1104970 Node 2 - 0x1104850 Node 3 - 0x11048d0 Node 5 - 0x1104810 Node 6 - 0x1104ab0 Node 6 - 0x1104ab0 Node 5 - 0x1104810
Complexity Analysis:
- Time Complexity: O(V + E) where V and E are the numbers of vertices and edges in the graph respectively.
- Auxiliary Space: O(V + E).
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!