[leetcode#133] Clone Graph

Source: Internet
Author: User

The problem:

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         /          \_/

My Analysis:
The implementation pattern used in Thisproblem is very classic in cloning a graph. The key Idea:use a hash map to store and retrieve the copy of a node. <original, copy>The basic idea was to use the invariant:1. We dequeue a node from the queue and then we scan the node ' s neighbors. We check if the neighbor node has already been traversaled by using the "Containkeys ()" method. 1.1 IFF the node is in the HashMap, we would don't make a copy forit.1.2 IFF the node is not in the hashmap and we make a copy for  ThisNeighbor node. Put the <neighbor_node, copy>Into the HashMap and enqueue the neighbor node.if(!map.containskey (Cur.neighbors.get (i))) {//This node have not been traversaledcopy =NewUndirectedgraphnode (Cur.neighbors.get (i). label);        Map.put (Cur.neighbors.get (i), copy); Queue.offer (Cur.neighbors.get (i));  Note1:we only enqueue nodes from neighbors list, which means all neighbors list of remaining nodes in the queue (until the dequeue) have not been copyed yet. Thus, forEach of the current node's Neghbor list, we need to fully copy it. for(inti = 0; I < cur.neighbors.size (); i++) {    if(!Map.containskey (Cur.neighbors.get (i)))    {    ...    } Map.get (cur). Neighbors.add (Map.get (Cur.neighbors.get (i))); Note2:to Use the invariant, we need-make necessary preparation forIt (dummy layer). We should suppose there is dummy layer copy of the starting node, and then put it into HashMap and enqueue the starting node.

My Solution:

 Public classSolution { Publicundirectedgraphnode Clonegraph (Undirectedgraphnode node) {if(node = =NULL)            return NULL; HashMap<undirectedgraphnode, undirectedgraphnode> map =NewHashmap<undirectedgraphnode, undirectedgraphnode> (); Queue<UndirectedGraphNode> queue =NewLinkedlist<undirectedgraphnode> ();                Undirectedgraphnode cur; Undirectedgraphnode Copy=NewUndirectedgraphnode (Node.label);        Queue.offer (node);                Map.put (node, copy);  while(!Queue.isempty ()) {cur=Queue.poll ();  for(inti = 0; I < cur.neighbors.size (); i++) {                if(!map.containskey (Cur.neighbors.get (i))) {//This node have not been traversaledcopy =NewUndirectedgraphnode (Cur.neighbors.get (i). label);                    Map.put (Cur.neighbors.get (i), copy);                Queue.offer (Cur.neighbors.get (i));            } map.get (cur). Neighbors.add (Map.get (Cur.neighbors.get (i))); }        }                returnmap.get (node); }}

[leetcode#133] Clone Graph

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.