-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path1_2_clone_graph.js
More file actions
48 lines (41 loc) · 1.11 KB
/
Copy path1_2_clone_graph.js
File metadata and controls
48 lines (41 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 133. Clone Graph
* Given a reference of a node in a connected undirected graph,
* return a deep copy (clone) of the graph. Each node in the graph contains
* a val (int) and a list (List[Node]) of its neighbors.
* Definition for a Node.
* function Node(val,neighbors) {
* this.val = val;
* this.neighbors = neighbors;
* };
*
* @param {Node} node
* @return {Node}
*/
function UndirectedGraphNode(v, n = []) {
this.val = v;
this.neighbors = n;
}
// use queue and breadth first search
function cloneGraph(graph) {
if (graph === null) {
return graph;
}
const queue = [graph];
// make initial copy
const rootCopy = new UndirectedGraphNode(graph.val);
const mapping = {};
mapping[graph.val] = rootCopy;
while (queue.length > 0) {
let currNode = queue.shift();
currNode.neighbors.forEach((neighbor) => {
if (!mapping[neighbor.val]) {
let newNode = new UndirectedGraphNode(neighbor.val);
mapping[neighbor.val] = newNode;
queue.push(neighbor);
}
mapping[currNode.val].neighbors.push(mapping[neighbor.val]);
});
}
return rootCopy;
};