# Why I got time limit exceeded, I use recursive to solve the problem

• /**

• 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;
}

``````Map<Integer, UndirectedGraphNode> memory = new HashMap<Integer, UndirectedGraphNode>();
return cloneGraph(node, memory);
``````

}

public UndirectedGraphNode cloneGraph(UndirectedGraphNode node, Map<Integer, UndirectedGraphNode> memory)
{
UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
memory.put(node.label, newNode);

``````for (int i = 0; i < node.neighbors.size(); i++)
{
UndirectedGraphNode neighbor = node.neighbors.get(i);
UndirectedGraphNode newNeighbor = memory.get(neighbor.label);

if(newNeighbor == null)
{
newNeighbor = cloneGraph(neighbor);
}