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 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 }
  • 相关阅读:
    Golang 版本发布 与 TIOBE 排名
    Golang 处理 Json(二):解码
    Golang 处理 Json(一):编码
    Bootstrap datetimepicker “dp.change” 时间/日期 选择事件
    Golang Vendor 包机制 及 注意事项
    Golang Vendor 包管理工具 glide 使用教程
    .yaml 文件格式简介
    【Go命令教程】命令汇总
    【Go命令教程】14. go env
    【Go命令教程】13. go tool cgo
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3375354.html
Copyright © 2011-2022 走看看