Using a hash map to map original nodes and clone nodes, then BFS fills the visited hash map while also filling the clone nodes. It is indeed quite clever.
public: // Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Node *cloneGraph(Node *node) { if (node == nullptr) { returnnullptr; }
while (!q.empty()) { cur = q.front(); q.pop(); for (Node *neighbor : cur->neighbors) { if (visited.count(neighbor) == 0) { // Not visited // Create the clone node corresponding to this node visited[neighbor] = newNode(neighbor->val); q.push(neighbor); } // Add the newly created clone node or the already visited node to the neighbor of the clone node corresponding to the front node of the queue visited[cur]->neighbors.push_back(visited[neighbor]); } }