forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhoyeongkwak.ts
More file actions
35 lines (31 loc) · 754 Bytes
/
hoyeongkwak.ts
File metadata and controls
35 lines (31 loc) · 754 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
/**
* Definition for _Node.
* class _Node {
* val: number
* neighbors: _Node[]
*
* constructor(val?: number, neighbors?: _Node[]) {
* this.val = (val===undefined ? 0 : val)
* this.neighbors = (neighbors===undefined ? [] : neighbors)
* }
* }
*
*/
/*
*/
function cloneGraph(node: _Node | null): _Node | null {
const clones = new Map<_Node, _Node>()
const dfs = (n: _Node) => {
if (n === null) return n
if (clones.has(n)) {
return clones.get(n)
}
const copy = new _Node(n.val)
clones.set(n, copy)
for (const neighbor of n.neighbors) {
copy.neighbors.push(dfs(neighbor))
}
return copy
}
return dfs(node)
};