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


  • 0
    I

    /**

    • 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);
      	}
      
      	newNode.neighbors.add(newNeighbor);
      }
      
      return newNode;
      

      }
      }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.