I tried to solve an algo question using JavaScript and got circular reference error, I can understand that because I use objects as the keys in the visited object, and since it's an unidirectional graph so it will have circular references. However, after I replaced the object with Map, I got the problem solved.
I read some docs on MDN but still couldn't understand how Map solves the circular reference issue under the hood. Can anyone shed me some lights on this?
Here's my code using normal object that caused circular reference error:
/**
* // Definition for a Node.
* function Node(val, neighbors) {
* this.val = val === undefined ? 0 : val;
* this.neighbors = neighbors === undefined ? [] : neighbors;
* };
*/
/**
* @param {Node} node
* @return {Node}
*/
var cloneGraph = function(node) {
if(!node){
return node;
}
const clone = new Node(node.val);
const queue = [node];
const visited = {node: clone};
while(queue.length){
let n = queue.shift();
for(let i of n.neighbors){
if(!(i in visited)){
queue.push(i);
visited[i] = new Node(i.val);
}
visited[n].neighbors.push(visited[i]);
}
}
return visited[node];
};
The output I got from printing the visited[node]:
{
node: { val: 1, neighbors: [] },
'[object Object]': <ref *1> {
val: 2,
neighbors: [ [Circular *1], [Circular *1], [Circular *1], [Circular *1] ]
}
}
And here's the code used Map and passed:
var cloneGraph = function(node) {
if(!node){
return node;
}
const clone = new Node(node.val);
const queue = [node];
const visited = new Map();
visited.set(node, clone);
while(queue.length){
let n = queue.shift();
for(let i of n.neighbors){
if(!visited.has(i)){
queue.push(i);
visited.set(i, new Node(i.val));
}
visited.get(n).neighbors.push(visited.get(i));
}
}
return visited.get(node);
};