-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclone-graph.cpp
More file actions
29 lines (28 loc) · 1.09 KB
/
clone-graph.cpp
File metadata and controls
29 lines (28 loc) · 1.09 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
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
//https://www.cnblogs.com/grandyang/p/4267628.html
//这道题目的题意一开始没有弄清楚,其实就是将一个连通图进行深拷贝。原图怎么样,运行完程序返回一个一模一样的图就可以了。
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
unordered_map<int,UndirectedGraphNode*> graph;
return clone(graph,node);
}
UndirectedGraphNode * clone(unordered_map<int,UndirectedGraphNode*> &graph,UndirectedGraphNode *node){
if(!node) return NULL;//null不是关键字 但是NULL是关键字。
if(graph.count(node->label))
return graph[node->label];
UndirectedGraphNode * copy=new UndirectedGraphNode(node->label);
graph[node->label]=copy;
for(auto e:node->neighbors){
copy->neighbors.push_back(clone(graph,e));
}
return copy;
}
};