zoukankan      html  css  js  c++  java
  • Clone Graph -- LeetCode

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

    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
             / 
             \_/
    思路:DFS。
    要点:用一个map记录所有的label与指针的pair。这样可以避免环以及创建重复的节点。
     1 /**
     2  * Definition for undirected graph.
     3  * struct UndirectedGraphNode {
     4  *     int label;
     5  *     vector<UndirectedGraphNode *> neighbors;
     6  *     UndirectedGraphNode(int x) : label(x) {};
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     //suppose these two node are already labelled
    12     void help(UndirectedGraphNode *originalNode, UndirectedGraphNode *copiedNode, unordered_map<int, UndirectedGraphNode*> &dict) {
    13         for (int i = 0; i < originalNode->neighbors.size(); i++) {
    14             int childLabel = originalNode->neighbors[i]->label;
    15             if (dict.count(childLabel) > 0) copiedNode->neighbors.push_back(dict[childLabel]);
    16             else {
    17                 UndirectedGraphNode *node = new UndirectedGraphNode(childLabel);
    18                 dict.insert(make_pair(childLabel, node));
    19                 copiedNode->neighbors.push_back(node);
    20                 help(originalNode->neighbors[i], node, dict);
    21             }
    22         }
    23     }
    24     UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
    25         if (node == NULL) return NULL;
    26         unordered_map<int, UndirectedGraphNode*> dict;
    27         UndirectedGraphNode *copiedNode = new UndirectedGraphNode(node->label);
    28         dict.insert(make_pair(node->label, copiedNode));
    29         help(node, copiedNode, dict);
    30         return copiedNode;
    31     }
    32 };
  • 相关阅读:
    如何画出高级感的曼哈顿图,Manhattan++工具介绍
    Failed to open .vcf.gz: could not load index
    Mouse Genome Informatics(MGI)数据库介绍
    JZ落选跟我们有什么关系
    GenTree:基因进化和功能分析
    对性染色体进行关联分析
    媲美GWAS Catalog,囊括45万人数据,778个表型,3千万个位点的公共数据库:GeneATLAS
    DDD理论学习系列(11)-- 工厂
    RabbitMQ知多少
    DDD理论学习系列(10)-- 聚合
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5812342.html
Copyright © 2011-2022 走看看