Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created December 1, 2019 04:22
Show Gist options
  • Save shixiaoyu/4ae59e07c8b5151151a3b232a3f22a1f to your computer and use it in GitHub Desktop.
Save shixiaoyu/4ae59e07c8b5151151a3b232a3f22a1f to your computer and use it in GitHub Desktop.
// exactly the same as BFS except used a stack to mimic the recursion, technically any BFS can be written
// in DFS by using a stack
public Node cloneGraphDFSUsingStack(Node node) {
if (node == null) {
return node;
}
Map<Node, Node> lookup = new HashMap<>();
Node t = new Node(node.val, new ArrayList<>());
lookup.put(node, t);
Stack<Node> stack = new Stack<>();
stack.push(node);
while (!stack.isEmpty()) {
Node cur = stack.pop();
for (Node n : cur.neighbors) {
Node copiedNeighbor = null;
if (!lookup.containsKey(n)) {
copiedNeighbor = new Node(n.val, new ArrayList<>());
stack.push(n);
lookup.put(n, copiedNeighbor);
} 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