Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created December 22, 2014 23:21
Show Gist options
  • Save kanrourou/47223bdaf481505d4c7e to your computer and use it in GitHub Desktop.
Save kanrourou/47223bdaf481505d4c7e to your computer and use it in GitHub Desktop.
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if (node == null)
return null;
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
LinkedList<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
queue.add(node);
map.put(node, new UndirectedGraphNode(node.label));
while (!queue.isEmpty()) {
UndirectedGraphNode curr = queue.removeFirst();
for (int i = 0; i < curr.neighbors.size(); i++) {
if (!map.containsKey(curr.neighbors.get(i))) {
queue.add(curr.neighbors.get(i));
map.put(curr.neighbors.get(i), new UndirectedGraphNode(curr.neighbors.get(i).label));
}
}
}
HashSet<UndirectedGraphNode> visited = new HashSet<UndirectedGraphNode>();
queue.add(node);
visited.add(node);
while (!queue.isEmpty()) {
UndirectedGraphNode curr = queue.removeFirst();
UndirectedGraphNode copy = map.get(curr);
for (int i = 0; i < curr.neighbors.size(); i++) {
copy.neighbors.add(map.get(curr.neighbors.get(i)));
if (!visited.contains(curr.neighbors.get(i))) {
queue.add(curr.neighbors.get(i));
visited.add(curr.neighbors.get(i));
}
}
}
return map.get(node);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment