zoukankan      html  css  js  c++  java
  • 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 from 0 to N - 1, where N is the total nodes in the graph.
    We use # as a separator for each node, and , as a separator for each neighbor of the node.
    As an example, consider the serialized graph {1,2#2#2}.
    The graph has a total of three nodes, and therefore contains three parts as separated by #.
    Connect node 0 to both nodes 1 and 2.
    Connect node 1 to node 2.
    Connect node 2 to node 2 (itself), thus forming a self-cycle.
    Visually, the graph looks like the following:

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

    Solution: 1. DFS. 2. BFS.

     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 
    12     // BFS
    13     UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
    14         if(!node) {
    15             return NULL;
    16         }
    17         unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> map; 
    18         queue<UndirectedGraphNode*> q;
    19         q.push(node);
    20         map[node] = new UndirectedGraphNode(node->label);
    21         
    22         while(!q.empty()) {
    23             UndirectedGraphNode* orgnode = q.front();
    24             q.pop();
    25             UndirectedGraphNode* newnode = map[orgnode]; 
    26             for(int i = 0; i < orgnode->neighbors.size(); i++) {
    27                 UndirectedGraphNode* orgneighbor = orgnode->neighbors[i];
    28                 if(map.find(orgneighbor) == map.end()) {
    29                     UndirectedGraphNode* newneighbor = new UndirectedGraphNode(orgneighbor->label);
    30                     map[orgneighbor] = newneighbor;
    31                     q.push(orgneighbor);
    32                 }
    33                 newnode->neighbors.push_back(map[orgneighbor]);
    34             }
    35         }
    36         return map[node];
    37     }
    38 };
  • 相关阅读:
    UIGestureRecognizer在多层视图中的触发问题
    mysql出现Waiting for table metadata lock的原因及解决方案
    SQL逆向工程
    自己总结的ruby on rails 查询方法
    hdu 1536 SG函数模板题
    spring 源码分析之BeanPostProcessor
    spring bean生命周期管理--转
    java.lang.Long cannot be cast to java.lang.Integer解决办法
    Mybatis之Oracle增删查改示例--转
    Anti-If: The missing patterns--转
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3659905.html
Copyright © 2011-2022 走看看