-
Notifications
You must be signed in to change notification settings - Fork 1
/
133. Clone Graph
37 lines (32 loc) · 1.04 KB
/
133. Clone Graph
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 {
Map<Integer, UndirectedGraphNode> map = new HashMap<>();
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null) return null;
return clone(node);
}
UndirectedGraphNode clone(UndirectedGraphNode node) {
//boundary case
if(node == null) return null;
if(map.containsKey(node.label))
return map.get(node.label);
//clone the node
UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
map.put(clone.label, clone);
for(UndirectedGraphNode neighbour : node.neighbors) {
clone.neighbors.add(clone(neighbour)); //use the clone function
}
return clone;
}
}
//dfs + hashmap
//0 1,2
//1 2,0
//2 2,0,1