Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created December 1, 2019 04:17
Show Gist options
  • Save shixiaoyu/e246172907449895a0330ad388bf3888 to your computer and use it in GitHub Desktop.
Save shixiaoyu/e246172907449895a0330ad388bf3888 to your computer and use it in GitHub Desktop.
public Node cloneGraphBFS(Node node) {
if (node == null) {
return node;
}
Map<Node, Node> lookup = new HashMap<>();
Queue<Node> q = new LinkedList<>();
q.add(node);
lookup.put(node, new Node(node.val, new ArrayList<>()));
while (!q.isEmpty()) {
Node cur = q.poll();
for (Node n : cur.neighbors) {
Node copiedNeighbor = null;
if (!lookup.containsKey(n)) {
// the neighbors would be populated later when it's popped out from the queue
copiedNeighbor = new Node(n.val, new ArrayList<>());
lookup.put(n, copiedNeighbor);
q.add(n);
} else {
copiedNeighbor = lookup.get(n);
}
lookup.get(cur).neighbors.add(copiedNeighbor);
}
}
return lookup.get(node);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment