-
Notifications
You must be signed in to change notification settings - Fork 0
/
Clone Graph.java
48 lines (43 loc) · 1.64 KB
/
Clone Graph.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
38
39
40
41
42
43
44
45
46
47
48
/*
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
Link: https://leetcode.com/problems/clone-graph/
Example: None
Solution: None
Source: None
*/
/**
* 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 node;
}
ArrayList<UndirectedGraphNode> nodes = new ArrayList<UndirectedGraphNode>();
nodes.add(node);
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
map.put(node, new UndirectedGraphNode(node.label));
int start = 0;
while (start < nodes.size()) {
List<UndirectedGraphNode> neighbors = nodes.get(start++).neighbors;
for (int i = 0; i < neighbors.size(); i++) {
if (!map.containsKey(neighbors.get(i))) {
map.put(neighbors.get(i), new UndirectedGraphNode(neighbors.get(i).label));
nodes.add(neighbors.get(i));
}
}
}
for (int i = 0; i < nodes.size(); i++) {
UndirectedGraphNode newNode = map.get(nodes.get(i));
for (int j = 0; j < nodes.get(i).neighbors.size(); j++) {
newNode.neighbors.add(map.get(nodes.get(i).neighbors.get(j)));
}
}
return map.get(node);
}
}