forked from soulmachine/algorithm-essentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclone-graph-2.java
More file actions
30 lines (30 loc) · 1.22 KB
/
clone-graph-2.java
File metadata and controls
30 lines (30 loc) · 1.22 KB
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
// Clone Graph
// BFS,时间复杂度O(n),空间复杂度O(n)
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null) return null;
// key is original node,value is copied node
HashMap<UndirectedGraphNode,UndirectedGraphNode> visited = new HashMap<>();
// each node in queue is already copied itself
// but neighbors are not copied yet
Queue<UndirectedGraphNode> q = new LinkedList<>();
q.offer(node);
visited.put(node, new UndirectedGraphNode(node.label));
while (!q.isEmpty()) {
UndirectedGraphNode cur = q.poll();
for (UndirectedGraphNode nbr : cur.neighbors) {
// a copy already exists
if (visited.containsKey(nbr)) {
visited.get(cur).neighbors.add(visited.get(nbr));
} else {
UndirectedGraphNode new_node =
new UndirectedGraphNode(nbr.label);
visited.put(nbr, new_node);
visited.get(cur).neighbors.add(new_node);
q.offer(nbr);
}
}
}
return visited.get(node);
}
}