-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.ts
32 lines (30 loc) · 948 Bytes
/
Solution.ts
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
/**
* 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 == null) return null;
const visited = new Map();
visited.set(node, new Node(node.val));
const queue = [node];
while (queue.length) {
const cur = queue.shift();
for (let neighbor of cur.neighbors || []) {
if (!visited.has(neighbor)) {
queue.push(neighbor);
const newNeighbor = new Node(neighbor.val, []);
visited.set(neighbor, newNeighbor);
}
const newNode = visited.get(cur);
newNode.neighbors.push(visited.get(neighbor));
}
}
return visited.get(node);
}