LeetCode-Clone Graph-克隆无向图

https://oj.leetcode.com/problems/clone-graph/

克隆一个可能有环的无向图。递归的重构出每个顶点即可。虽然有环,但是每个结点的label提供了该结点的唯一标示。可以使用一个map记录该标识下结点的地址。

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
typedef UndirectedGraphNode scnode;
class Solution {
public:
    map cm;
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if (node==NULL) return NULL;
        int cl=node->label;
        if (cm.find(cl)!=cm.end()) return cm[cl];
        scnode *cur=new scnode(cl);
        cm[cl]=cur;
        vector  &neis=node->neighbors;
        for (int i=0;ineighbors.push_back(cloneGraph(p));
        }
        return cur;
    }
};

  

转载于:https://www.cnblogs.com/yangsc/p/4013595.html

你可能感兴趣的:(LeetCode-Clone Graph-克隆无向图)