Can some one help me to find why my code is taking long time?


  • 0
    A
    public UndirectedGraphNode GraphDFS(UndirectedGraphNode node) {
    	    if (node == null)
    		    return node;
    	    Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();
    	    UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
    	    map.put(node, newNode);
    	    dfs(node, newNode, map);
    	   return newNode;
        }
    
    private void dfs(UndirectedGraphNode node, UndirectedGraphNode newNode,
    		Map<UndirectedGraphNode, UndirectedGraphNode> map) {
    	if (node == null)
    		return;
    	for (UndirectedGraphNode neighbor : node.neighbors) {
    		if (node == neighbor) {
    			newNode.neighbors.add(newNode);
    			continue;
    		}
    		UndirectedGraphNode newNeighbor = null;
    		if (!map.containsKey(neighbor)) {
    			newNeighbor = new UndirectedGraphNode(neighbor.label);
    			map.put(neighbor, newNeighbor);
    		} else {
    			newNeighbor = map.get(neighbor);
    		}
    		newNode.neighbors.add(newNeighbor);
    		dfs(neighbor, newNeighbor, map);
    	}
    }

Log in to reply
 

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