You are pushing each of the neighbors into the queue, which is a bad idea. You only want to push a neighbor node into the queue only when the neighbor node is not a node you have visited before.
Why? Because the graph could contain cycles and you want to prevent that in your cloning process.
The other problem with your solution is the following line:
UndirectedGraphNode *target = new UndirectedGraphNode(source -> label);
Imagine your algorithm finish cloning all neighbors (nodes A
, B
, C
) of the starting node into nodes A'
, B'
, and C'
. It retrieves the next element from the queue which is node A'
. And your above code basically clone A'
again to A''
. Did you see the problem? You are storing the references of neighbors of A
into A''
, while it should be stored into A'
.