|
| 1 | +/** |
| 2 | + * TC: O(V + E) |
| 3 | + * ๋ชจ๋ ์ ์ ๋ฅผ ๋ฐฉ๋ฌธํ๊ฒ ๋๊ณ |
| 4 | + * ๋ฐฉ๋ฌธํ ์ ์ ์์ ์ฐ๊ฒฐ๋ ๊ฐ์ ์ queue์ ์ถ๊ฐํ๋ ๋ฐ๋ณต๋ฌธ์ ์คํํฉ๋๋ค. |
| 5 | + * ๋ฐ๋ผ์ ์๊ฐ๋ณต์ก๋๋ ์ ์ + ๊ฐ์ ์ ์ ํ์ ์ผ๋ก ๋น๋กํฉ๋๋ค. |
| 6 | + * |
| 7 | + * SC: O(V + E) |
| 8 | + * memory, visitedNodeVal ์์ V๋งํผ ๋ฐ์ดํฐ ๊ณต๊ฐ์ ๊ฐ์ง๋๋ค. |
| 9 | + * ๊ทธ๋ฆฌ๊ณ queue์์ ์ต๋ ๋ชจ๋ ๊ฐ์ ๊ฐฏ์ * 2 ๋งํผ ๊ฐ๊ฒ ๋ฉ๋๋ค. |
| 10 | + * ๋ฐ๋ผ์ O(V + 2E) = O(V + E)๋ก ๊ณ์ฐํ์ต๋๋ค. |
| 11 | + * |
| 12 | + * V: vertex, E: edge |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * // Definition for a _Node. |
| 17 | + * function _Node(val, neighbors) { |
| 18 | + * this.val = val === undefined ? 0 : val; |
| 19 | + * this.neighbors = neighbors === undefined ? [] : neighbors; |
| 20 | + * }; |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {_Node} node |
| 25 | + * @return {_Node} |
| 26 | + */ |
| 27 | +var cloneGraph = function (node) { |
| 28 | + if (!node) { |
| 29 | + return null; |
| 30 | + } |
| 31 | + |
| 32 | + const memory = new Map(); |
| 33 | + const visitedNodeVal = new Set(); |
| 34 | + |
| 35 | + return bfsClone(node); |
| 36 | + |
| 37 | + // 1. bfs๋ก ์ํํ๋ฉด์ deep cloneํ graph์ head๋ฅผ ๋ฐํ |
| 38 | + function bfsClone(start) { |
| 39 | + const queue = [start]; |
| 40 | + const clonedHeadNode = new _Node(start.val); |
| 41 | + memory.set(start.val, clonedHeadNode); |
| 42 | + |
| 43 | + while (queue.length > 0) { |
| 44 | + const current = queue.shift(); |
| 45 | + if (visitedNodeVal.has(current.val)) { |
| 46 | + continue; |
| 47 | + } |
| 48 | + |
| 49 | + const clonedCurrentNode = getCloneNode(current.val); |
| 50 | + |
| 51 | + for (const neighbor of current.neighbors) { |
| 52 | + const clonedNeighborNode = getCloneNode(neighbor.val); |
| 53 | + clonedCurrentNode.neighbors.push(clonedNeighborNode); |
| 54 | + |
| 55 | + queue.push(neighbor); |
| 56 | + } |
| 57 | + |
| 58 | + visitedNodeVal.add(current.val); |
| 59 | + } |
| 60 | + |
| 61 | + return clonedHeadNode; |
| 62 | + } |
| 63 | + |
| 64 | + // 2. memory์ val์ ํด๋นํ๋ node ๋ฐํ (์์ ๊ฒฝ์ฐ ์์ฑ) |
| 65 | + function getCloneNode(val) { |
| 66 | + if (!memory.has(val)) { |
| 67 | + const node = new _Node(val); |
| 68 | + memory.set(val, node); |
| 69 | + return node; |
| 70 | + } |
| 71 | + |
| 72 | + return memory.get(val); |
| 73 | + } |
| 74 | +}; |
0 commit comments