-
Notifications
You must be signed in to change notification settings - Fork 4
/
133_cloneGraph.java
37 lines (33 loc) · 1.43 KB
/
133_cloneGraph.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
30
31
32
33
34
35
36
37
/**
* 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;
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
HashMap<UndirectedGraphNode,UndirectedGraphNode> map = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
map.put(node,newNode);
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
queue.add(node);
while(!queue.isEmpty()){
UndirectedGraphNode current = queue.remove();
List<UndirectedGraphNode> currentNeighbors = current.neighbors;
for(UndirectedGraphNode currentNeighbor: currentNeighbors){
if(map.containsKey(currentNeighbor)){
map.get(current).neighbors.add(map.get(currentNeighbor));
} else{
UndirectedGraphNode copy = new UndirectedGraphNode(currentNeighbor.label);
map.put(currentNeighbor,copy);
queue.add(currentNeighbor);
map.get(current).neighbors.add(copy);
}
}
}
return newNode;
}
}