# Could anyone help me solve the TimeOut problem?

• ``````public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null) return null;
HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();

queue.offer(node);

while(!queue.isEmpty()) {
UndirectedGraphNode currNode = queue.poll();
ArrayList<UndirectedGraphNode> list = currNode.neighbors;
// If the node is not in the map, create a new copy node and store the pair in HashMap
if(!map.containsKey(currNode)) {
UndirectedGraphNode newNode = new UndirectedGraphNode(currNode.label);
map.put(currNode, newNode);
}
for(int i = 0; i < list.size(); i ++) {
UndirectedGraphNode neighborNode = list.get(i);
queue.off(neighborNode);
}
}
}
``````

}

in the code above, I used Queue and HashMap. The Queue is used to traversal the graph, and map is used to store the node and copy node pairs.

• The error you are thinking of, where your algorithm takes too long to solve the problem, is "Time Limit Exceeded." TimeOut is a problem with the server, such as there being too much traffic at that time. Try submitting again.

• You should try to split this problem into two parts. In the first part you need to construct each node. In the second part you should construct all the links. May it be helpful !

• ``````while(!queue.isEmpty()) {
UndirectedGraphNode currNode = queue.poll();
ArrayList<UndirectedGraphNode> list = currNode.neighbors;
// If the node is not in the map, create a new copy node and store the pair in HashMap
if(!map.containsKey(currNode)) {
UndirectedGraphNode newNode = new UndirectedGraphNode(currNode.label);
map.put(currNode, newNode);
}
for(int i = 0; i < list.size(); i ++) {
UndirectedGraphNode neighborNode = list.get(i);
queue.off(neighborNode);