A 10-Line DFS Solution (105ms)


  • 1
    L
    public class Solution {
        Dictionary<UndirectedGraphNode, UndirectedGraphNode> mapping = new Dictionary<UndirectedGraphNode, UndirectedGraphNode>();
        public UndirectedGraphNode CloneGraph(UndirectedGraphNode node) {
            UndirectedGraphNode newNode = null;
            if(node != null && mapping.ContainsKey(node)) newNode = mapping[node];
            else if (node != null){
                newNode = new UndirectedGraphNode(node.label);
                mapping.Add(node, newNode);
                foreach(var nb in node.neighbors)
                    newNode.neighbors.Add(CloneGraph(nb));
            }
            return newNode;
        }
    }

Log in to reply
 

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