forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmmyeon.ts
48 lines (41 loc) ยท 1.52 KB
/
mmyeon.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class _Node {
val: number;
neighbors: _Node[];
constructor(val?: number, neighbors?: _Node[]) {
this.val = val === undefined ? 0 : val;
this.neighbors = neighbors === undefined ? [] : neighbors;
}
}
/**
* @link https://leetcode.com/problems/clone-graph/description/
*
* ์ ๊ทผ ๋ฐฉ๋ฒ :
* - ์ฃ์ง ์ผ์ด์ค : ์ฃผ์ด์ง ๋
ธ๋๊ฐ null์ด๋ฉด ๊ทธ๋๋ก ๋ฆฌํด
* - ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๋
ธ๋์ธ์ง ํ์ธ : ๋ฐฉ๋ฌธํ ๋
ธ๋์ธ ๊ฒฝ์ฐ, ์ ์ฅ๋ ๋ณต์ฌ ๋
ธ๋ ๋ฆฌํดํด์ ์ค๋ณต ์์ฑ ๋ฐฉ์ง
* - ์๋ก์ด ๋
ธ๋ ํด๋ก ํ๊ณ visited ๋งต์ ์ ์ฅ
* - ํด๋น ๋
ธ๋์ ์ด์ ๋
ธ๋๋ ์ํํ๋ฉด์ ๋ณต์
* - ํด๋ก ๋ ๋
ธ๋ ๋ฆฌํด
*
* ์๊ฐ๋ณต์ก๋ : O(n + e)
* - n์ ๋
ธ๋์ ๊ฐ์, e๋ ๋
ธ๋ ์ฐ๊ฒฐํ๋ ์ฃ์ง์ ๊ฐ์
* - ๋ชจ๋ ๋
ธ๋ ์ํํ๋ฉด์ ๊ฐ ๋
ธ๋์ ์ด์ ํ์
*
* ๊ณต๊ฐ๋ณต์ก๋ : O(n)
* - ๋ชจ๋ ๋
ธ๋๋ฅผ ํด๋ก ํด์ visited ๋งต์ ์ ์ฅ๋๋ฏ๋ก O(n)
* - ๊ทธ๋ํ๊ฐ ์ ํ ๊ตฌ์กฐ์ธ ์ต์
์ ๊ฒฝ์ฐ, ์ฌ๊ท ํธ์ถ ์คํ์ด O(n)
*/
function cloneGraph(node: _Node | null): _Node | null {
if (!node) return null;
const visited = new Map<number, _Node>();
const cloneNode = (node: _Node): _Node => {
if (visited.has(node.val)) return visited.get(node.val) as _Node;
const clonedNode = new _Node(node.val);
visited.set(node.val, clonedNode);
for (const neighbor of node.neighbors) {
const clonedNeighbor = cloneNode(neighbor);
clonedNode.neighbors.push(clonedNeighbor);
}
return clonedNode;
};
return cloneNode(node);
}