algorithm-in-python/graph/cloneGraph.cpp

47 lines
999 B
C++
Raw Permalink Normal View History

2019-06-11 16:26:24 +08:00
/* mbinary
#########################################################################
# File : cloneGraph.cpp
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2019-04-16 09:41
# Description:
#########################################################################
*/
2020-04-15 12:28:20 +08:00
class Solution
{
2019-03-15 16:37:02 +08:00
public:
2020-04-15 12:28:20 +08:00
map<Node*, Node*> st;
Node *cloneGraph(Node *node)
{
Node* ret = new Node(node->val, vector<Node*>());
st[node] = ret;
for (auto x : node->neighbors) {
2019-03-15 16:37:02 +08:00
auto p = st.find(x);
2020-04-15 12:28:20 +08:00
if (p == st.end()) {
2019-03-15 16:37:02 +08:00
ret->neighbors.push_back(cloneGraph(x));
2020-04-15 12:28:20 +08:00
} else ret->neighbors.push_back(p->second);
2019-03-15 16:37:02 +08:00
}
2020-04-15 12:28:20 +08:00
2019-03-15 16:37:02 +08:00
return ret;
}
};
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/