Accepted C# DFS solution


  • 0
    M
    /**
    
    • Definition for undirected graph.

    • public class UndirectedGraphNode {

    • public int label;
      
    • public IList<UndirectedGraphNode> neighbors;
      
    • public UndirectedGraphNode(int x) { label = x; neighbors = new List<UndirectedGraphNode>(); }
      
    • };
      */
      public class Solution {

      private Dictionary<UndirectedGraphNode, UndirectedGraphNode> visit = new Dictionary<UndirectedGraphNode, UndirectedGraphNode>();
      public UndirectedGraphNode CloneGraph(UndirectedGraphNode node) {
      if(node == null) return null;

       if(!visit.ContainsKey(node))
       {
           //Note that, you need to put the new copied node to the Dict
           visit[node] = new UndirectedGraphNode(node.label);
           
           foreach(var neibor in node.neighbors)
           {
               visit[node].neighbors.Add(CloneGraph(neibor));
           }
           
       }
       
       return visit[node];
      

      }
      }


Log in to reply
 

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