• leetcode--Clone Graph


    Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors

     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     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
    11         UndirectedGraphNode newNode = null;
    12         if(node != null){
    13             Map<UndirectedGraphNode, UndirectedGraphNode> org = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
    14             ArrayList<UndirectedGraphNode> alist = new ArrayList<UndirectedGraphNode>();
    15             alist.add(node);
    16             for(int i = 0; i < alist.size(); ++i){
    17                 UndirectedGraphNode temp = alist.get(i);
    18                 UndirectedGraphNode cloneNode = null;
    19                 if(!org.containsKey(temp)){
    20                     cloneNode = new UndirectedGraphNode(temp.label);
    21                     org.put(temp, cloneNode);
    22                 }
    23                 else
    24                     cloneNode = org.get(temp);                    
    25                 List<UndirectedGraphNode> nei = temp.neighbors;
    26                 for(int j = 0; j < nei.size(); ++j){
    27                     if(org.containsKey(nei.get(j)))
    28                         cloneNode.neighbors.add(org.get(nei.get(j)));
    29                     else{
    30                         UndirectedGraphNode clNode = new UndirectedGraphNode(nei.get(j).label);
    31                         alist.add(nei.get(j));
    32                         org.put(nei.get(j), clNode);
    33                         cloneNode.neighbors.add(clNode);
    34                     }                            
    35                 }
    36             }
    37             newNode = org.get(node);
    38         }
    39         return newNode;
    40     }
    41 }
  • 相关阅读:
    springboot2.1.3使用jdbcTemplate
    httpclient4.5.2 Post请求支持http和https
    springboot2.1.3+spring-session2.1.4分库处理
    mysql查看当前实时连接数
    springboot2.1.3+Junit4 单元测试
    subprocess.Popen()详解
    matplotlib 设置图形大小时 figsize 与 dpi 的关系
    matplotlib之subplot
    matplotlib.pyplot.plot()参数详解
    plt.rcParams属性总结
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3535486.html
Copyright © 2020-2023  润新知