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 }

 

转载于:https://www.cnblogs.com/averillzheng/p/3535486.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值