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 };
  • 相关阅读:
    在MYSQL中插入当前时间,就象SQLSERVER的GETDATE()一样,以及对mysql中的时间日期操作。
    mysql使用default来设置字段的默认值
    MySQL关于check约束无效的解决办法
    C# 加密算法汇总
    REST,Web 服务,REST-ful 服务
    C# HTML 生成 PDF
    SQL Server Connection Pooling (ADO.NET)
    ADO.NET Connection Pooling at a Glance
    正则表达式
    开发 ASP.NET vNext 初步总结(使用Visual Studio 2015 Preview )
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5812342.html
Copyright © 2011-2022 走看看