forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHoonDongKang.ts
More file actions
65 lines (52 loc) · 1.7 KB
/
HoonDongKang.ts
File metadata and controls
65 lines (52 loc) · 1.7 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
/**
* [Problem]: [133] Clone Graph
* (https://leetcode.com/problems/longest-repeating-character-replacement/description/)
*/
// 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 {
//시간복잡도 O(n)
//공간복잡도 O(n)
function dfsFunc(node: _Node | null): _Node | null {
if (!node) return null;
const map = new Map<_Node, _Node>();
function dfs(node: _Node): _Node {
if (map.has(node)) return map.get(node)!;
const copy = new _Node(node.val);
map.set(node, copy);
for (const neighbor of node.neighbors) {
copy.neighbors.push(dfs(neighbor));
}
return copy;
}
return dfs(node);
}
//시간복잡도 O(n)
//공간복잡도 O(n)
function bfsFunc(node: _Node | null): _Node | null {
if (!node) return null;
const map = new Map<_Node, _Node>();
const queue: _Node[] = [];
const clone = new _Node(node.val);
map.set(node, clone);
queue.push(node);
while (queue.length > 0) {
const cur = queue.shift()!;
for (const neighbor of cur.neighbors) {
if (!map.has(neighbor)) {
map.set(neighbor, new _Node(neighbor.val));
queue.push(neighbor);
}
map.get(cur)!.neighbors.push(map.get(neighbor)!);
}
}
return clone;
}
}