-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.js
37 lines (33 loc) · 827 Bytes
/
res.js
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
/**
* res.js
* @authors Joe Jiang ([email protected])
* @date 2017-04-16 22:11:56
*
* Problem: Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
*
* Definition for undirected graph.
* function UndirectedGraphNode(label) {
* this.label = label;
* this.neighbors = []; // Array of UndirectedGraphNode
* }
*/
/**
* @param {UndirectedGraphNode} graph
* @return {UndirectedGraphNode}
*/
let cloneGraph = function(graph) {
// if (!graph) return graph;
let res = {};
return iterateGraph(graph);
function iterateGraph(subgraph) {
if (!subgraph) {
return subgraph;
}
let id = subgraph.label;
if (!res[id]) {
res[id] = new UndirectedGraphNode(id);
res[id].neighbors = subgraph.neighbors.map(iterateGraph);
}
return res[id];
}
};