Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
- use BFS to solve this problem.
- use a Map in javascript to store a mapping between nodes in original graph and nodes in new graph.
- when using BFS to traverse the original graph, if a neighbor is already in the map, it means the corresponding node has been created and we just need to connect two nodes in the new graph
- when using BFS to traverse the original graph, if a neighbor isn’t in the map, we create a new node in the new graph, push the neighbor in the queue and connect two nodes in the new graph.
/**
* @param {UndirectedGraphNode} graph
* @return {UndirectedGraphNode}
*/
var cloneGraph = function(graph) {
if (graph === null) {
return null;
}
//bfs
var queue = [];
queue.push(graph);
var map = new Map();
var head = new UndirectedGraphNode(graph.label);
map.set(graph, head);
while (queue.length !== 0) {
var curr = queue.shift();
// console.log(curr);
var neighbors = curr.neighbors;
for (var i = 0; i < neighbors.length; i++) {
var neighbor = neighbors[i];
// this neighbor has not been visited
if (map.get(neighbor) === undefined) {
var copyNeighbor = new UndirectedGraphNode(neighbor.label);
map.set(neighbor, copyNeighbor);
map.get(curr).neighbors.push(copyNeighbor);
queue.push(neighbor);
// this neighbor has been visited
} else {
map.get(curr).neighbors.push(map.get(neighbor));
}
}
}
return head;
};