Skip to content

Commit ce0eb2e

Browse files
committed
clone graph solution
1 parent d679ed8 commit ce0eb2e

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

clone-graph/hyer0705.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Definition for _Node.
3+
* class _Node {
4+
* val: number
5+
* neighbors: _Node[]
6+
*
7+
* constructor(val?: number, neighbors?: _Node[]) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.neighbors = (neighbors===undefined ? [] : neighbors)
10+
* }
11+
* }
12+
*
13+
*/
14+
15+
function cloneGraph(node: _Node | null): _Node | null {
16+
if (!node) return null;
17+
18+
const cloned = new Map<number, _Node>();
19+
20+
const queue: _Node[] = [];
21+
22+
const copied = new _Node(node.val);
23+
cloned.set(node.val, copied);
24+
25+
queue.push(node);
26+
27+
let pointer = 0;
28+
29+
while (pointer < queue.length) {
30+
const current = queue[pointer++];
31+
32+
const copiedNode = cloned.get(current.val)!;
33+
34+
for (const neighbor of current.neighbors) {
35+
if (!cloned.has(neighbor.val)) {
36+
const copiedNeighbor = new _Node(neighbor.val);
37+
cloned.set(neighbor.val, copiedNeighbor);
38+
39+
queue.push(neighbor);
40+
}
41+
copiedNode.neighbors.push(cloned.get(neighbor.val)!);
42+
}
43+
}
44+
45+
return copied;
46+
}

0 commit comments

Comments
 (0)