Skip to content

Commit a4a6325

Browse files
committed
solve: clone graph
1 parent 29244bf commit a4a6325

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

clone-graph/wogha95.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* TC: O(E)
3+
* graph에 연결된 edge만큼 queue에 추가, 제거하며 순회한다.
4+
*
5+
* SC: O(V + E)
6+
* cloned graph만큼 공간 복잡도 생성해야한다.
7+
*
8+
* V: vertex, E: edge
9+
*/
10+
11+
/**
12+
* // Definition for a _Node.
13+
* function _Node(val, neighbors) {
14+
* this.val = val === undefined ? 0 : val;
15+
* this.neighbors = neighbors === undefined ? [] : neighbors;
16+
* };
17+
*/
18+
19+
/**
20+
* @param {_Node} node
21+
* @return {_Node}
22+
*/
23+
var cloneGraph = function (node) {
24+
if (!node) {
25+
return null;
26+
}
27+
28+
const memory = new Map();
29+
const visitedNodeVal = new Set();
30+
31+
return bfsClone(node);
32+
33+
// 1. bfs로 순회하면서 deep clone한 graph의 head를 반환
34+
function bfsClone(start) {
35+
const queue = [start];
36+
const clonedHeadNode = new _Node(start.val);
37+
memory.set(start.val, clonedHeadNode);
38+
39+
while (queue.length > 0) {
40+
const current = queue.shift();
41+
if (visitedNodeVal.has(current.val)) {
42+
continue;
43+
}
44+
45+
const clonedCurrentNode = getCloneNode(current.val);
46+
47+
for (const neighbor of current.neighbors) {
48+
const clonedNeighborNode = getCloneNode(neighbor.val);
49+
clonedCurrentNode.neighbors.push(clonedNeighborNode);
50+
51+
queue.push(neighbor);
52+
}
53+
54+
visitedNodeVal.add(current.val);
55+
}
56+
57+
return clonedHeadNode;
58+
}
59+
60+
// 2. memory에 val에 해당하는 node 반환 (없을 경우 생성)
61+
function getCloneNode(val) {
62+
if (!memory.has(val)) {
63+
memory.set(val, new _Node(val));
64+
}
65+
66+
return memory.get(val);
67+
}
68+
};

0 commit comments

Comments
 (0)