Clone Graph_Week18

Clone Graph_Week18

题目:(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 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.
Visually, the graph looks like the following:

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

难度: Medium

解题思路:
题意:给定一个图,复制这个图。
这道题很好理解,也不是很难,重点在于需要不能创建重复的点。
比如说,先建立了点0,而得知0的邻居有1和2,然而再访问1,得知1的邻居有0和2,若此时再创建一个点0,那么new出来的这个新的节点,将会是一个跟原有的0完全不同的节点,那么复制出来的图就是完全不同的图了。
所以本题的重点在于复习如何高效地使用深度搜索、或者广度搜索来完成访问这个图,并且不重复创建点地复制整张图。

代码如下:

/**
 * 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 NULL;
        }
        if (map.find(node) == map.end()) { //判断当前访问的节点是否已创建 
            map[node] = new UndirectedGraphNode(node->label);
            for (UndirectedGraphNode* neigh : node->neighbors) {
                //利用深度优先搜索,递归访问每个邻居,对于每个邻居又访问它的邻居
                //当该邻居已存在时,会被上面的判断条件阻断再次创建的可能性 
                map[node]->neighbors.push_back(cloneGraph(neigh));
            } 
        }
        return map[node];
    } 
private:
    unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> map;
};

猜你喜欢

转载自blog.csdn.net/m0_38072045/article/details/78907254