forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhyer0705.ts
More file actions
46 lines (35 loc) · 1006 Bytes
/
hyer0705.ts
File metadata and controls
46 lines (35 loc) · 1006 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
41
42
43
44
45
46
/**
* 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 {
if (!node) return null;
const cloned = new Map<number, _Node>();
const queue: _Node[] = [];
const copied = new _Node(node.val);
cloned.set(node.val, copied);
queue.push(node);
let pointer = 0;
while (pointer < queue.length) {
const current = queue[pointer++];
const copiedNode = cloned.get(current.val)!;
for (const neighbor of current.neighbors) {
if (!cloned.has(neighbor.val)) {
const copiedNeighbor = new _Node(neighbor.val);
cloned.set(neighbor.val, copiedNeighbor);
queue.push(neighbor);
}
copiedNode.neighbors.push(cloned.get(neighbor.val)!);
}
}
return copied;
}