示例#1
0
        public Node CloneGraph(Node node)
        {
            if (node == null)
            {
                return(null);
            }
            var cloned = new Dictionary <Node, Node>();

            return(GetNodeOrCreate(node, cloned));
        }
示例#2
0
        Node GetNodeOrCreate(Node node, Dictionary <Node, Node> cloned)
        {
            if (cloned.ContainsKey(node))
            {
                return(cloned[node]);
            }
            var nodeClone = new Node();

            nodeClone.val       = node.val;
            nodeClone.neighbors = new List <Node>();
            cloned[node]        = nodeClone;
            foreach (var i in node.neighbors)
            {
                var nb = GetNodeOrCreate(i, cloned);
                nodeClone.neighbors.Add(nb);
            }
            return(nodeClone);
        }