-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloneGraph.java
More file actions
28 lines (25 loc) · 850 Bytes
/
Copy pathCloneGraph.java
File metadata and controls
28 lines (25 loc) · 850 Bytes
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
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CloneGraph {
private Map<Integer, UndirectedGraphNode> map = new HashMap<>();
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null) return null;
if(map.containsKey(node.label)) return map.get(node.label);
UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
map.put(node.label, clone);
if(node.neighbors != null){
List<UndirectedGraphNode> neighbors = node.neighbors;
for(UndirectedGraphNode neighbor : neighbors){
clone.neighbors.add(cloneGraph(neighbor));
}
}
return clone;
}
}
class UndirectedGraphNode {
int label;
List<UndirectedGraphNode> neighbors;
UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
}