-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathclone-graph.js
More file actions
40 lines (33 loc) · 876 Bytes
/
clone-graph.js
File metadata and controls
40 lines (33 loc) · 876 Bytes
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
// Source : https://leetcode.com/problems/clone-graph/
// Author : Han Zichi
// Date : 2016-08-28
/**
* Definition for undirected graph.
* function UndirectedGraphNode(label) {
* this.label = label;
* this.neighbors = []; // Array of UndirectedGraphNode
* }
*/
/**
* @param {UndirectedGraphNode} graph
* @return {UndirectedGraphNode}
*/
var cloneGraph = function(graph) {
if (!graph)
return null;
var hash = {};
return dfs(graph);
function dfs(node) {
var label = node.label;
var newNode = new UndirectedGraphNode(label);
hash[label] = newNode;
for (var i = 0, len = node.neighbors.length; i < len; i++) {
var item = node.neighbors[i];
if (hash[item.label] !== undefined)
newNode.neighbors.push(hash[item.label]);
else
newNode.neighbors.push(dfs(item));
}
return newNode;
}
};