Created
December 1, 2019 04:17
-
-
Save shixiaoyu/e246172907449895a0330ad388bf3888 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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