Short C# DFS Recursive Solution with Dictionary(Hashmap)-- 104 ms


  • 0
    L
    public class Solution {
        Dictionary<int, UndirectedGraphNode> dict = new Dictionary<int, UndirectedGraphNode>();
        public UndirectedGraphNode CloneGraph(UndirectedGraphNode node) {
            if(node == null) return null;
            if(dict.ContainsKey(node.label))
                return dict[node.label];
            UndirectedGraphNode nd = new UndirectedGraphNode(node.label);
            dict.Add(nd.label, nd);
            foreach(UndirectedGraphNode n in node.neighbors)
                nd.neighbors.Add(CloneGraph(n));
            return nd;
        }
    }

Log in to reply
 

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