forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrumbs22.cpp
More file actions
60 lines (51 loc) ยท 1.2 KB
/
crumbs22.cpp
File metadata and controls
60 lines (51 loc) ยท 1.2 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
#include <vector>
#include <iostream>
using namespace std;
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;
}
};
/*
std::vector<T> v;
v.emplace_back(arg1, arg2, ...); // ์์ฑ์ ์ธ์๋ฅผ ๋ฐ๋ก ์ ๋ฌํด ์ปจํ
์ด๋ ์์์ ์ง์ T ๊ฐ์ฒด๋ฅผ ์์ฑ
*/
#include <unordered_map>
#include <queue>
class Solution {
public:
Node* cloneGraph(Node* node) {
if (!node)
return (nullptr);
unordered_map<Node*, Node*> m;
queue<Node*> q;
m[node] = new Node(node->val); // ์์ ๋
ธ๋๋ฅผ ๋ณต์ ํ๊ณ ๋งต๊ณผ ํ์ ๋ฑ๋ก
q.push(node);
// BFS
while (!q.empty()) {
Node* cur = q.front();
q.pop();
for (Node* nei : cur->neighbors) {
// ์์ง ๋ณต์ ํ์ง ์์ ๋
ธ๋์ผ ๋
if (!m.count(nei)) {
m[nei] = new Node(nei->val);
q.push(nei);
}
m[cur]->neighbors.push_back(m[nei]); // ํ์ฌ ๋ณต์ ๋ณธ์ ์ด ์ด์์ ๋ณต์ ๋ณธ์ ์ฐ๊ฒฐ
}
}
return m[node];
}
};