JasonChang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

BFS 用hashmap记录对应关系

 1 public class Solution {
 2     public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         if(node == null)
 6             return null;
 7         LinkedList<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
 8         Map<UndirectedGraphNode, UndirectedGraphNode> mymap = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
 9         UndirectedGraphNode head = new UndirectedGraphNode(node.label);
10         queue.add(node);
11         mymap.put(node, head);
12         while(!queue.isEmpty())
13         {
14             UndirectedGraphNode nodeinqueue = queue.poll();
15             for(UndirectedGraphNode i:nodeinqueue.neighbors)
16             {
17                 if(mymap.containsKey(i))
18                     mymap.get(nodeinqueue).neighbors.add(mymap.get(i));
19                 else
20                 {
21                     UndirectedGraphNode tmp = new UndirectedGraphNode(i.label);
22                     mymap.get(nodeinqueue).neighbors.add(tmp);
23                     mymap.put(i, tmp);
24                     queue.add(i);
25                 }
26             }
27         }
28         return head;
29     }
30 }

 

posted on 2013-11-11 07:26  JasonChang  阅读(176)  评论(0编辑  收藏  举报