133. Clone Graph

Posted tianzeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了133. Clone Graph相关的知识,希望对你有一定的参考价值。

Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph contains a label (int) and a list (List[UndirectedGraphNode]) of its neighbors. There is an edge between the given node and each of the nodes in its neighbors.


OJ‘s undirected graph serialization (so you can understand error output):

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 #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

 

Visually, the graph looks like the following:

       1
      /      /       0 --- 2
         /          \\_/

Note: The information about the tree serialization is only meant so that you can understand error output if you get a wrong answer. You don‘t need to understand the serialization to solve the problem.

 

DFS解析:

1.在复制图的时候需要深拷贝,所以需要new一个对象。关于深拷贝和钱拷贝:https://www.cnblogs.com/tianzeng/p/9431556.html

2.需要用map来存储结点。原因:

  1>.map中不允许有重复的键,用map可用label当做键,neighbors为值。

  2>.假如:A与B有相邻的边,在处理A的时候发现A的邻居B,则加入把B加入到A的neighbors中;此图为无向图,在处理B的时候也会发现B的邻居A,则也会把A加入到B的邻居中,这样以来就形成了

      一个环,所以如果用map容器来存储,则在处理B时,想要把A加入B的邻居时,map会检测到已经存在A,则不会执行加入操作,也不会形成环。(用unordered_map与map作用一样,只是

        查找变快)。

  3>.用DFS的时候,需要找到最后一个没有分支的结点所以mp.find(node)==mp.end()

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution 
{
    public:
        UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) 
        {
            
            if(node==NULL)
                return nullptr;
            
            if(mp.find(node)==mp.end())
            {
                mp[node]=new UndirectedGraphNode(node->label);
                for(auto n:node->neighbors)
                    mp[node]->neighbors.push_back(cloneGraph(n));
            }
            return mp[node];
        }
    private:
        unordered_map<UndirectedGraphNode *,UndirectedGraphNode *> mp;
};

 

 

第一次刷LeetCode,没什么经验,根据https://blog.csdn.net/lanxu_yy/article/details/17848219 的题目顺序来的


以上是关于133. Clone Graph的主要内容,如果未能解决你的问题,请参考以下文章

133. Clone Graph (Graph)

133. Clone Graph

133. Clone Graph

LeetCode-133-Clone Graph

[LeetCode] 133. Clone Graph

133. Clone Graph