Skip to content

Commit 1c0c8a7

Browse files
committed
Solution: Clone Graph
1 parent 211abc0 commit 1c0c8a7

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

clone-graph/flynn.cpp

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* 풀이
3+
* - BFS와 해시맵을 사용하여 풀이합니다
4+
*
5+
* Big O
6+
* - N: 주어진 노드의 개수
7+
* - E: 주어진 노드의 간선의 개수
8+
*
9+
* - Time complexity: O(E)
10+
* - 한 Node에서 다른 Node로 향하는 모든 edge를 두번씩 탐색합니다 (두 방향으로 연결되어 있기 때문)
11+
* - Space complexity: O(N)
12+
* - 해시맵에 최대 N개의 노드를 저장합니다
13+
*/
14+
15+
/*
16+
// Definition for a Node.
17+
class Node {
18+
public:
19+
int val;
20+
vector<Node*> neighbors;
21+
Node() {
22+
val = 0;
23+
neighbors = vector<Node*>();
24+
}
25+
Node(int _val) {
26+
val = _val;
27+
neighbors = vector<Node*>();
28+
}
29+
Node(int _val, vector<Node*> _neighbors) {
30+
val = _val;
31+
neighbors = _neighbors;
32+
}
33+
};
34+
*/
35+
36+
class Solution {
37+
public:
38+
Node* cloneGraph(Node* node) {
39+
if (node == nullptr) return nullptr;
40+
41+
unordered_map<Node*, Node*> node_map;
42+
node_map[node] = new Node(node->val);
43+
44+
queue<Node*> q;
45+
q.push(node);
46+
47+
while (!q.empty()) {
48+
Node* p = q.front();
49+
q.pop();
50+
51+
for (Node* neighbor : p->neighbors) {
52+
// 방문한 적이 없는 노드일 경우
53+
if (node_map.find(neighbor) == node_map.end()) {
54+
// node_map에 새로운 노드를 복제하여 추가
55+
node_map[neighbor] = new Node(neighbor->val);
56+
57+
// 큐에 추가
58+
q.push(neighbor);
59+
}
60+
61+
node_map[p]->neighbors.push_back(node_map[neighbor]);
62+
}
63+
}
64+
65+
return node_map[node];
66+
}
67+
};

0 commit comments

Comments
 (0)