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

    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
             / 
             \_/
    

    直接用HashMap来做应该是最简单的,这个对十字链表也可以。使用hashmap来存储node的对应关系。

     1 /**
     2  * Definition for undirected graph.
     3  * class UndirectedGraphNode {
     4  *     int label;
     5  *     ArrayList<UndirectedGraphNode> neighbors;
     6  *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
     7  * };
     8  */
     9 public class Solution {
    10     HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
    11     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
    12         map.clear();
    13         return cloneNode(node);
    14     }
    15      
    16     private UndirectedGraphNode cloneNode(UndirectedGraphNode node)
    17     {
    18         if (node == null) return null;
    19         if (map.containsKey(node)) return map.get(node);
    20         else
    21         {
    22             UndirectedGraphNode copy = new UndirectedGraphNode(node.label);
    23             map.put(node, copy);
    24             for (UndirectedGraphNode n : node.neighbors)
    25             {
    26                 copy.neighbors.add(cloneNode(n));
    27             }
    28             return copy;
    29         }
    30     }
    31 }
  • 相关阅读:
    谈执着
    SQL表自连接用法
    Mysql group by 排序问题
    php自动生成mysql的触发代码。
    XSS CSRF 攻击
    [微信开发利器]微信内移动前端开发抓包调试工具fiddler使用教程
    微信JS-SDK]微信公众号JS开发之卡券领取功能详解
    优化与重构的思考
    c语言 13
    c语言 13
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3375354.html
Copyright © 2020-2023  润新知