Leetcode-133. Clone Graph

来源:互联网 发布:取名软件免费版 编辑:程序博客网 时间:2024/06/03 10:01

133. Clone Graph

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.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 node 0 to both nodes 1 and 2.Second node is labeled as 1. Connect node 1 to node 2.Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

目标:克隆一个无向图,其中,图的节点由以下结构表示。

  • Definition for undirected graph.
  • struct UndirectedGraphNode {
  • int label;
  • vector<UndirectedGraphNode *> neighbors;
  • UndirectedGraphNode(int x) : label(x) {};
  • };

    在solution里添加一个map<UndirectedGraphNode *, UndirectedGraphNode *> m来保存克隆图(Key 为节点,Value 为该节点的邻接节点)。用DFS算法遍历全图,若当前节点已在克隆图中,则返回克隆图中的该节点,否则创立新节点加入克隆图中,并添加其所有邻接节点。

class Solution {  public:      UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {          if(!node)             return NULL;          if(m.count(node))             return m[node];          UndirectedGraphNode *nodeClone = new UndirectedGraphNode(node->label);        m[node] = nodeClone;        for(int i=0;i<node->neighbors.size();i++)          {            UndirectedGraphNode *temp = cloneGraph(node->neighbors[i]);            if(temp != NULL)                nodeClone->neighbors.push_back(temp);        }        return nodeClone;    }  private:      map<UndirectedGraphNode *, UndirectedGraphNode *> m;  };  
0 0