版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DouMiaoO_Oo/article/details/88771355
Clone Graph
Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.
Note:
- The number of nodes will be between 1 and 100.
- The undirected graph is a simple graph, which means no repeated edges and no self-loops in the graph.
- Since the graph is undirected, if node p has node q as neighbor, then node q must have node p as neighbor too.
- You must return the copy of the given node as a reference to the cloned graph.
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
Node* cloneGraph(Node* node) {
unordered_map<Node*, Node*> m;
helper(node, m);
return m[node];
}
private:
void helper(Node* node, unordered_map<Node*, Node*>& m){
if(m.find(node) != m.end()) return;
Node* nnode = new Node(node->val, vector<Node*>(node->neighbors.size(), NULL));
m[node] = nnode;
for(int i = 0; i < node->neighbors.size(); ++i){
helper((node->neighbors)[i] , m);
nnode->neighbors[i] = m[node->neighbors[i]];
}
}
};