zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    ping
    android Handler总结
    配置网络测试环境的批处理
    shell 的选项解析
    [转] Linux 中共享库的搜索
    SecureCRT 脚本一则(0720.Rev.1)
    使用 Wget 完成自动 Web 认证(推 portal)
    shell 选项解析之需求一:多路径自动补全
    getopts 的简单模拟(09.12 Rev)
    ThinkPHP框架使用心得三 RBAC权限控制(2)简要原理
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3535486.html
Copyright © 2011-2022 走看看