forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHC-kang.ts
More file actions
63 lines (51 loc) · 1.34 KB
/
HC-kang.ts
File metadata and controls
63 lines (51 loc) · 1.34 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
/**
* https://leetcode.com/problems/clone-graph
* T.C. O(N)
* S.C. O(N)
*/
function cloneGraph(node: _Node | null): _Node | null {
if (!node) return null;
const map = new Map<number, _Node>();
return dfs(node);
function dfs(node: _Node): _Node {
if (map.has(node.val)) return map.get(node.val)!;
const newNode = new _Node(node.val);
map.set(node.val, newNode);
for (let neighbor of node.neighbors) {
newNode.neighbors.push(dfs(neighbor));
}
return newNode;
}
}
/**
* T.C. O(N)
* S.C. O(N)
*/
function cloneGraph(node: _Node | null): _Node | null {
if (!node) return null;
const map = new Map<number, _Node>();
const stack = [node];
const newNode = new _Node(node.val);
map.set(node.val, newNode);
while (stack.length) {
const node = stack.pop()!;
const newNode = map.get(node.val)!;
for (let neighbor of node.neighbors) {
if (!map.has(neighbor.val)) {
stack.push(neighbor);
const newNeighbor = new _Node(neighbor.val);
map.set(neighbor.val, newNeighbor);
}
newNode.neighbors.push(map.get(neighbor.val)!);
}
}
return newNode;
}
class _Node {
val: number;
neighbors: _Node[];
constructor(val?: number, neighbors?: _Node[]) {
this.val = val === undefined ? 0 : val;
this.neighbors = neighbors === undefined ? [] : neighbors;
}
}