"""# Definition for a Node.class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else []"""classSolution:defcloneGraph(self,node:'Node')->'Node':visited=defaultdict()defclone(node):ifnodeisNone:returnNoneifnodeinvisited:returnvisited[node]c=Node(node.val)visited[node]=cforeinnode.neighbors:c.neighbors.append(clone(e))returncreturnclone(node)
/*// Definition for a Node.class Node { public int val; public List<Node> neighbors; public Node() { val = 0; neighbors = new ArrayList<Node>(); } public Node(int _val) { val = _val; neighbors = new ArrayList<Node>(); } public Node(int _val, ArrayList<Node> _neighbors) { val = _val; neighbors = _neighbors; }}*/classSolution{privateMap<Node,Node>visited=newHashMap<>();publicNodecloneGraph(Nodenode){if(node==null){returnnull;}if(visited.containsKey(node)){returnvisited.get(node);}Nodeclone=newNode(node.val);visited.put(node,clone);for(Nodee:node.neighbors){clone.neighbors.add(cloneGraph(e));}returnclone;}}
/** * Definition for a Node. * type Node struct { * Val int * Neighbors []*Node * } */funccloneGraph(node*Node)*Node{visited:=map[*Node]*Node{}varclonefunc(node*Node)*Nodeclone=func(node*Node)*Node{ifnode==nil{returnnil}if_,ok:=visited[node];ok{returnvisited[node]}c:=&Node{node.Val,[]*Node{}}visited[node]=cfor_,e:=rangenode.Neighbors{c.Neighbors=append(c.Neighbors,clone(e))}returnc}returnclone(node)}