The idea is to do a BFS traversal of the graph and while visiting a node make a clone node of it (a copy of original node). If a node is encountered which is already visited then it already has a clone node.
How to keep track of the visited/cloned nodes?
A HashMap/Map is required in order to maintain all the nodes which have already been created.
Key stores: Reference/Address of original Node
Value stores: Reference/Address of cloned Node
A copy of all the graph nodes has been made, how to connect clone nodes?
While visiting the neighboring vertices of a node u get the corresponding cloned node for u , let’s call that cloneNodeU , now visit all the neighboring nodes for u and for each neighbor find the corresponding clone node(if not found create one) and then push into the neighboring vector of cloneNodeU node.
How to verify if the cloned graph is a correct?
Do a BFS traversal before and after the cloning of graph. In BFS traversal display the value of a node along with its address/reference.
Compare the order in which nodes are displayed, if the values are same but the address/reference is different for both the traversals than the cloned graph is correct.
Output in Java:
BFS traversal of a graph before cloning Value of Node 1 Address of Node GraphNode@15db9742 Value of Node 2 Address of Node GraphNode@6d06d69c Value of Node 4 Address of Node GraphNode@7852e922 Value of Node 3 Address of Node GraphNode@4e25154f BFS traversal of a graph after cloning Value of Node 1 Address of Node GraphNode@70dea4e Value of Node 2 Address of Node GraphNode@5c647e05 Value of Node 4 Address of Node GraphNode@33909752 Value of Node 3 Address of Node GraphNode@55f96302
Output in C++:
BFS Traversal before cloning Value of Node 1 Address of Node 0x24ccc20 Value of Node 2 Address of Node 0x24ccc50 Value of Node 4 Address of Node 0x24cccb0 Value of Node 3 Address of Node 0x24ccc80 BFS Traversal after cloning Value of Node 1 Address of Node 0x24cd030 Value of Node 2 Address of Node 0x24cd0e0 Value of Node 4 Address of Node 0x24cd170 Value of Node 3 Address of Node 0x24cd200
This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.