-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path133.java
29 lines (29 loc) · 1.08 KB
/
133.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node==null) return null;
Map<Integer,UndirectedGraphNode> map = new HashMap<>();
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
map.put(node.label,newNode);
Queue<UndirectedGraphNode> queue = new LinkedList<>();
queue.offer(node);
while(!queue.isEmpty()){
UndirectedGraphNode n = queue.poll();
for(UndirectedGraphNode neighbor : n.neighbors){
if(!map.containsKey(neighbor.label)){
map.put(neighbor.label,new UndirectedGraphNode(neighbor.label));
queue.offer(neighbor);
}
map.get(n.label).neighbors.add(map.get(neighbor.label));
}
}
return newNode;
}
}