forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJeehay28.ts
More file actions
67 lines (51 loc) · 1.44 KB
/
Jeehay28.ts
File metadata and controls
67 lines (51 loc) · 1.44 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class _Node {
val: number;
neighbors: _Node[];
constructor(val?: number, neighbors?: _Node[]) {
this.val = val === undefined ? 0 : val;
this.neighbors = neighbors === undefined ? [] : neighbors;
}
}
// TC: O(V + E), where V is the number of vertices and E is the number of edges
// SC: O(V + E)
function cloneGraph(node: _Node | null): _Node | null {
// 1: [2, 4]
// 2: [1, 3]
// 3: [2, 4]
// 4: [1, 3]
const clones = new Map<_Node, _Node>();
// original Node: cloned Node
if (!node) return null;
const dfs = (node: _Node) => {
if (clones.has(node)) {
return clones.get(node);
}
const clone = new _Node(node.val);
clones.set(node, clone);
for (const nei of node.neighbors) {
clone.neighbors.push(dfs(nei)!);
}
return clone;
};
return dfs(node)!;
}
// TC: O(V + E)
// SC: O(V + E)
// function cloneGraph(node: _Node | null): _Node | null {
// if (!node) return null;
// const clone: _Node = new _Node(node.val);
// const clones = new Map<_Node, _Node>();
// clones.set(node, clone);
// const queue: _Node[] = [node]; // BFS -> use queue
// while (queue.length > 0) {
// const node = queue.shift()!;
// for (const nei of node.neighbors) {
// if (!clones.has(nei)) {
// clones.set(nei, new _Node(nei.val));
// queue.push(nei);
// }
// clones.get(node)!.neighbors.push(clones.get(nei)!);
// }
// }
// return clone;
// }