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 };
  • 相关阅读:
    获取当前季的js
    C#获取文件大小
    SQL Server 2005 Express Edition 傻瓜式安装
    SET XACT_ABORT ON
    Resignation letter
    Exchange Web Services Managed API 1.0 入门
    Please let us know in case of any issues
    33条C#、.Net经典面试题目及答案
    c# 修饰词public, protected, private,internal,protected的区别
    EXEC DTS
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5812342.html
Copyright © 2011-2022 走看看