Skip to content

Commit ec462ec

Browse files
Update Clone_Graph.js
1 parent 3cbeff2 commit ec462ec

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

LeetcodeProblems/Clone_Graph.js

+33-1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ You don't need to understand the serialization to solve the problem.
4040
* }
4141
*/
4242

43+
44+
// SOLUTION 1 Using DFS
4345
/**
4446
* @param {UndirectedGraphNode} graph
4547
* @return {UndirectedGraphNode}
@@ -64,4 +66,34 @@ var dfs = function(graph, visited) {
6466
}
6567

6668
return newNode;
67-
}
69+
}
70+
71+
// SOLUTION 2 Using DFS
72+
var cloneGraphBFS = function(graph) {
73+
if(graph === null)
74+
return graph;
75+
76+
var visitedMap = {};
77+
var queue = [graph];
78+
var copyReturn = new UndirectedGraphNode(graph.label);
79+
visitedMap[graph.label] = copyReturn;
80+
81+
while(queue.length > 0) {
82+
var node = queue.shift();
83+
var nodeCopied = visitedMap[node.label];
84+
85+
for(var i = 0; i < node.neighbors.length; i++) {
86+
var neighbor = node.neighbors[i];
87+
88+
if(!visitedMap[neighbor.label]) {
89+
var copyNeighbor = new UndirectedGraphNode(neighbor.label);
90+
visitedMap[neighbor.label] = copyNeighbor;
91+
queue.push(neighbor);
92+
}
93+
94+
nodeCopied.neighbors.push(visitedMap[neighbor.label]);
95+
}
96+
}
97+
98+
return copyReturn;
99+
}

0 commit comments

Comments
 (0)