[Leetcode] [JAVA] Clone Graph, Copy List with Random Pointer

Source: Internet
Author: User

Clone Graph:

Clone an undirected graph. Each node in the graph contains a and label a lists of its neighbors .


OJ ' s undirected graph serialization:

Nodes is labeled uniquely.

We use # as a separator for each node, and as , a separator for node label and each neighbor of the node.

As an example, consider the serialized graph {0,1,2#1,2#2,2} .

The graph has a total of three nodes, and therefore contains three parts as separated by # .

    1. First node is labeled as 0 . Connect node to 0 both nodes 1 and 2 .
    2. Second node is labeled as 1 . Connect node to 1 node 2 .
    3. Third node is labeled as 2 . Connect node 2 to Node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

       1      /      /       0---2         /          \_/



The traversal of graphs is nothing more than depth first and breadth first. The breadth-first search is used here.
The key point of the problem is full cloning, that is, each node encountered must be copied out, and if there is a connected edge (pointer), also need to copy out.
It can be realized by using HashMap to correspond the original node with the clone node. When traversing to node x, also get X ', all adjacent nodes of X are discussed, if it is a new neighbor (HASHMAP) n, then copy an n ', copy point n ' and X ' connected, and the corresponding two (N,n ') into the HashMap, the new adjacent node (N) into the queue.
If you find that node n has been traversed, you only need to copy the point n ' to the copy point X ' of the current traversal point, which is to copy an edge.

Code:
1  Publicundirectedgraphnode Clonegraph (Undirectedgraphnode node) {2         if(node==NULL)3             return NULL;4queue<undirectedgraphnode> q =NewLinkedlist<undirectedgraphnode>();5Hashmap<undirectedgraphnode, undirectedgraphnode> HM =NewHashmap<undirectedgraphnode, undirectedgraphnode>();6         7 q.add (node);8Undirectedgraphnode copy =NewUndirectedgraphnode (Node.label);9 hm.put (node, copy);Ten          while(!q.isempty ()) One         { AUndirectedgraphnode temp =Q.poll (); -Undirectedgraphnode tempcopy =Hm.get (temp); -List<undirectedgraphnode> N =temp.neighbors; the              for(intI=0;i<n.size (); i++) { -Undirectedgraphnode TEMPN =N.get (i); -                 if(!Hm.containskey (TEMPN)) { -Undirectedgraphnode Copyn =NewUndirectedgraphnode (Tempn.label); + TempCopy.neighbors.add (Copyn); - hm.put (TEMPN, Copyn); + Q.add (TEMPN); A                 } at                 Else { - TempCopy.neighbors.add (Hm.get (TEMPN)); -                 } -             } -         } -         returncopy; in}

Copy List with Random Pointer:

A linked list is given such this each node contains an additional random pointer which could point to all node in the list or null.

Return a deep copy of the list.

This feeling like a simplified version of the clone graph (the number of adjacent nodes is up to 2), do not know whether the understanding is wrong, in short, the use of the above ideas can be passed. The only difference is to discuss the case where the node is empty, only adjacent nodes that are not empty need to be discussed.

Code:

1  PublicRandomlistnode copyrandomlist (Randomlistnode head) {2         if(head==NULL)3             return NULL;4queue<randomlistnode> q =NewLinkedlist<randomlistnode>();5 Q.add (head);6Hashmap<randomlistnode,randomlistnode> HM =NewHashmap<randomlistnode,randomlistnode>();7Randomlistnode headcopy =NewRandomlistnode (Head.label);8 Hm.put (head,headcopy);9          while(!q.isempty ())Ten         { OneRandomlistnode temp =Q.poll (); ARandomlistnode copytemp =Hm.get (temp); -Randomlistnode ntemp =Temp.next; -Randomlistnode rtemp =Temp.random; the             if(ntemp!=NULL) -             { -                 if(!Hm.containskey (ntemp)) { -Randomlistnode Copynext =NewRandomlistnode (Ntemp.label); +Copytemp.next =Copynext; - Hm.put (ntemp,copynext); + Q.add (ntemp); A                 } at                 Else -Copytemp.next =Hm.get (ntemp); -             } -             if(rtemp!=NULL) -             { -                 if(!Hm.containskey (rtemp)) { inRandomlistnode Copyrandom =NewRandomlistnode (Rtemp.label); -Copytemp.random =Copyrandom; to Hm.put (rtemp,copyrandom); + Q.add (rtemp); -                 } the                 Else *Copytemp.random =Hm.get (rtemp); $             }Panax Notoginseng         } -         returnheadcopy; the}

[Leetcode] [JAVA] Clone Graph, Copy List with Random Pointer

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.