LeetCode: 133. 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
         / \          \_/  解题思路 —— 递归分治
记录复制过的,正在复制的节点, 递归地处理每一个没有处理过的节点。
AC代码
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */
class Solution {
public:
    UndirectedGraphNode *cloneGraphRef(UndirectedGraphNode *node,
                                       map<int, UndirectedGraphNode*>& recordedNode) {
        if(node == nullptr) return nullptr;
        if(recordedNode.find(node->label) != recordedNode.end()) 
        {
            return recordedNode[node->label]; // 已经处理过, 直接返回存储的值
        }
        UndirectedGraphNode* pCurNode = new UndirectedGraphNode(node->label);
        // 记录当前的节点
        recordedNode[pCurNode->label] = pCurNode;
        // 分治:分别处理每一个 neighbors 节点
        for(size_t i = 0; i < node->neighbors.size(); ++i)
        {
            pCurNode->neighbors.push_back(cloneGraphRef(node->neighbors[i], recordedNode));
        }
        return pCurNode;
    }
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        map<int, UndirectedGraphNode*> recordedNode;
        return cloneGraphRef(node, recordedNode);
    }
};
京公网安备 11010502036488号