forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobzva.cpp
More file actions
67 lines (58 loc) ยท 1.62 KB
/
obzva.cpp
File metadata and controls
67 lines (58 loc) ยท 1.62 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
/**
* ํ์ด
* - BFS์ ํด์๋งต์ ์ฌ์ฉํ์ฌ ํ์ดํฉ๋๋ค
*
* Big O
* - N: ์ฃผ์ด์ง ๋
ธ๋์ ๊ฐ์
* - E: ์ฃผ์ด์ง ๋
ธ๋์ ๊ฐ์ ์ ๊ฐ์
*
* - Time complexity: O(E)
* - ํ Node์์ ๋ค๋ฅธ Node๋ก ํฅํ๋ ๋ชจ๋ edge๋ฅผ ๋๋ฒ์ฉ ํ์ํฉ๋๋ค (๋ ๋ฐฉํฅ์ผ๋ก ์ฐ๊ฒฐ๋์ด ์๊ธฐ ๋๋ฌธ)
* - Space complexity: O(N)
* - ํด์๋งต์ ์ต๋ N๊ฐ์ ๋
ธ๋๋ฅผ ์ ์ฅํฉ๋๋ค
*/
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
Node* cloneGraph(Node* node) {
if (node == nullptr) return nullptr;
unordered_map<Node*, Node*> node_map;
node_map[node] = new Node(node->val);
queue<Node*> q;
q.push(node);
while (!q.empty()) {
Node* p = q.front();
q.pop();
for (Node* neighbor : p->neighbors) {
// ๋ฐฉ๋ฌธํ ์ ์ด ์๋ ๋
ธ๋์ผ ๊ฒฝ์ฐ
if (node_map.find(neighbor) == node_map.end()) {
// node_map์ ์๋ก์ด ๋
ธ๋๋ฅผ ๋ณต์ ํ์ฌ ์ถ๊ฐ
node_map[neighbor] = new Node(neighbor->val);
// ํ์ ์ถ๊ฐ
q.push(neighbor);
}
node_map[p]->neighbors.push_back(node_map[neighbor]);
}
}
return node_map[node];
}
};