Skip to content

Commit bce0345

Browse files
authored
Update Clone Graph.java
1 parent ff4c9b6 commit bce0345

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

Java/Clone Graph.java

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
M
2-
1519966780
2+
1533605472
33
tags: DFS, BFS, Graph
44

55
给一个graph node, 每个node有list of neighbors. 复制整个graph, return new head node.
6+
7+
实现起来就好像在crawl urls.
68

79
#### 思想
810
- Use HashMap to mark cloned nodes.
@@ -132,20 +134,19 @@ public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
132134
return null;
133135
}
134136
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
135-
map.put(node, new UndirectedGraphNode(node.label));
137+
map.put(node, new UndirectedGraphNode(node.label)); // copy root
136138

137-
Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
139+
Queue<UndirectedGraphNode> queue = new LinkedList<>();
138140
queue.offer(node);
139141

140142
while(!queue.isEmpty()) {
141143
UndirectedGraphNode curr = queue.poll();
142144
for (UndirectedGraphNode neighbor: curr.neighbors) {
143-
// Copy neighbors
144-
if (!map.containsKey(neighbor)) {
145+
if (!map.containsKey(neighbor)) { // Init neighbors
145146
queue.offer(neighbor);
146147
map.put(neighbor, new UndirectedGraphNode(neighbor.label));
147148
}
148-
map.get(curr).neighbors.add(map.get(neighbor));
149+
map.get(curr).neighbors.add(map.get(neighbor)); // link neighbor
149150
}
150151
}
151152

0 commit comments

Comments
 (0)