Clone Graph
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use# as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by #.
- First node is labeled as
0. Connect node0to both nodes1and2. - Second node is labeled as
1. Connect node1to node2. - Third node is labeled as
2. Connect node2to node2(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
思考: 实现深度复制,但会出现环形,避免每个节点多次复制,可以将已经复制过的节点进行保存,label是唯一确定的,所以用label和node联系起来,然后进行递归即可。
java代码:
- Map<Integer,UndirectedGraphNode> mp = new HashMap<Integer,UndirectedGraphNode>();
- UndirectedGraphNode helper(UndirectedGraphNode node,Map<Integer,UndirectedGraphNode> mp) {
- if(node==null) return null;
- if(mp.containsKey(node.label)) return mp.get(node.label);
- UndirectedGraphNode new_node = new UndirectedGraphNode(node.label);
- mp.put(node.label,new_node);
- for(int i=0;i<node.neighbors.size();i++) {
- UndirectedGraphNode child = cloneGraph(node.neighbors.get(i));
- new_node.neighbors.add(child);
- }
- return new_node;
- }
- public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
- if(node == null) return null;
- UndirectedGraphNode new_node = helper(node,mp);
- return new_node;
- }
C++代码:
- UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
- UndirectedGraphNode *root =NULL;
- if(node==NULL) return root;
- unordered_map<int,UndirectedGraphNode *> track;
- root = cloneGraph(node,track);
- return root;
- }
- UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node, unordered_map<int,UndirectedGraphNode *> & track) {
- if(!node) return NULL;
- if(track.count(node->label)) return track[node->label];
- UndirectedGraphNode *root = new UndirectedGraphNode(node->label);
- root->neighbors.resize(node->neighbors.size());
- //root->label=node->label;
- track[node->label]=root;
- for(int i=0;i<node->neighbors.size();i++) {
- root->neighbors[i] = cloneGraph(node->neighbors[i],track);
- }
- return root;
- }

浙公网安备 33010602011771号