-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy path克隆图.js
More file actions
30 lines (29 loc) · 674 Bytes
/
克隆图.js
File metadata and controls
30 lines (29 loc) · 674 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
/**
* // Definition for a Node.
* function Node(val, neighbors) {
* this.val = val === undefined ? 0 : val;
* this.neighbors = neighbors === undefined ? [] : neighbors;
* };
*/
/**
* @param {Node} node
* @return {Node}
133. 克隆图
*/
var cloneGraph = function(node) {
let map = new Map();
const dfs = (dot) => {
if(!dot) return;
let backup = new Node(dot.val);
map.set(dot, backup);
dot.neighbors.forEach(ne => {
if(!map.has(ne)) {
dfs(ne);
}
backup.neighbors.push(map.get(ne));
})
return backup;
}
dfs(node);
return map.get(node);
};