forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwogha95.js
More file actions
74 lines (61 loc) ยท 1.83 KB
/
wogha95.js
File metadata and controls
74 lines (61 loc) ยท 1.83 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
66
67
68
69
70
71
72
73
74
/**
* TC: O(V + E)
* ๋ชจ๋ ์ ์ ๋ฅผ ๋ฐฉ๋ฌธํ๊ฒ ๋๊ณ
* ๋ฐฉ๋ฌธํ ์ ์ ์์ ์ฐ๊ฒฐ๋ ๊ฐ์ ์ queue์ ์ถ๊ฐํ๋ ๋ฐ๋ณต๋ฌธ์ ์คํํฉ๋๋ค.
* ๋ฐ๋ผ์ ์๊ฐ๋ณต์ก๋๋ ์ ์ + ๊ฐ์ ์ ์ ํ์ ์ผ๋ก ๋น๋กํฉ๋๋ค.
*
* SC: O(V + E)
* memory, visitedNodeVal ์์ V๋งํผ ๋ฐ์ดํฐ ๊ณต๊ฐ์ ๊ฐ์ง๋๋ค.
* ๊ทธ๋ฆฌ๊ณ queue์์ ์ต๋ ๋ชจ๋ ๊ฐ์ ๊ฐฏ์ * 2 ๋งํผ ๊ฐ๊ฒ ๋ฉ๋๋ค.
* ๋ฐ๋ผ์ O(V + 2E) = O(V + E)๋ก ๊ณ์ฐํ์ต๋๋ค.
*
* V: vertex, E: edge
*/
/**
* // Definition for a _Node.
* function _Node(val, neighbors) {
* this.val = val === undefined ? 0 : val;
* this.neighbors = neighbors === undefined ? [] : neighbors;
* };
*/
/**
* @param {_Node} node
* @return {_Node}
*/
var cloneGraph = function (node) {
if (!node) {
return null;
}
const memory = new Map();
const visitedNodeVal = new Set();
return bfsClone(node);
// 1. bfs๋ก ์ํํ๋ฉด์ deep cloneํ graph์ head๋ฅผ ๋ฐํ
function bfsClone(start) {
const queue = [start];
const clonedHeadNode = new _Node(start.val);
memory.set(start.val, clonedHeadNode);
while (queue.length > 0) {
const current = queue.shift();
if (visitedNodeVal.has(current.val)) {
continue;
}
const clonedCurrentNode = getCloneNode(current.val);
for (const neighbor of current.neighbors) {
const clonedNeighborNode = getCloneNode(neighbor.val);
clonedCurrentNode.neighbors.push(clonedNeighborNode);
queue.push(neighbor);
}
visitedNodeVal.add(current.val);
}
return clonedHeadNode;
}
// 2. memory์ val์ ํด๋นํ๋ node ๋ฐํ (์์ ๊ฒฝ์ฐ ์์ฑ)
function getCloneNode(val) {
if (!memory.has(val)) {
const node = new _Node(val);
memory.set(val, node);
return node;
}
return memory.get(val);
}
};