Leetcode Clone Graph

Source: Internet
Author: User

Copy an image without a direction. The structure of the graph has a label, a vector, and the node he wants to connect to. Can self-cycle, is the vector can exist themselves. For example:

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         /          \_/
Idea: In the beginning, I thought of using BFS, but I need to decide whether the node has been processed because there is a loop. Avoid the cycle of death with a can O1 time to access the value of the existence of the east to save the node has been visited, that is, map, or set, I use set to save access, and then two queue to synchronize the walk, and the node copied to another root, Then que and que2 respectively indicate the post-processing nodes that need to continue the BFS process. Non-iterative:
/** Definition for undirected graph. * struct UNDIRECTEDGRAPHNODE {* int label; * Vector<undirectedgraphno De *> neighbors; * Undirectedgraphnode (int x): label (x) {}; * }; */classSolution { Public: Undirectedgraphnode*clonegraph (Undirectedgraphnode *node) {        if(!node)returnnode; //if (node-neighbors). Size () = = 0) return node;Queue<undirectedgraphnode *>que, que2;        Que.push (node); Undirectedgraphnode*root =NewUndirectedgraphnode (node, label), *tmp, *subnode, *TMP2; Unordered_set<UndirectedGraphNode*>Uset;        Que2.push (root);  while(!Que.empty ()) {tmp=Que.front (); TMP2=Que2.front ();            Uset.insert (TMP);            Que.pop ();            Que2.pop ();  for(inti =0; I < tmp-neighbors.size (); ++i) {if(TMP-neighbors[i] = =tmp) subnode=TMP2; Elsesubnode=NewUndirectedgraphnode (TMP, Neighbors[i)label); TMP2-Neighbors.push_back (subnode); if(Uset.count (TMP, neighbors[i]) = =0) {Que.push (TMP-Neighbors[i]);                Que2.push (subnode); }            }        }        returnRoot; }};
View Code

But the time has expired, may recently the cold brain is not flexible ah.

I do not know why the above with two queue will time out AH. If you switch to map, you will not time out:

Unordered_map (Undirectedgraphnode *, Undirectedgraphnode *) copied; refers to whether or not node of key is copied in the corresponding node of value.

Because it is BFS to use a que to save itself has been copied, but his neighbors has not replicated the node. Then initializing que will push a node, and Copied[node] is the new node assigned to Node->label.

Then, depending on whether the que is empty.

/** Definition for undirected graph. * struct UNDIRECTEDGRAPHNODE {* int label; * Vector<undirectedgraphno De *> neighbors; * Undirectedgraphnode (int x): label (x) {}; * }; */classSolution { Public: Undirectedgraphnode*clonegraph (Undirectedgraphnode *node) {        if(!node)returnnode; Unordered_map<undirectedgraphnode *, Undirectedgraphnode *>copied; Queue<undirectedgraphnode *>que;        Que.push (node); Copied[node]=NewUndirectedgraphnode (Node-label);  while(!Que.empty ()) {Undirectedgraphnode*cur =Que.front ();            Que.pop ();  for(inti =0; I < cur-neighbors.size (); ++i) {if(Copied.count (cur->Neighbors[i])) Copied[cur]Neighbors.push_back (Copied[cur,Neighbors[i]]); Else{Undirectedgraphnode*new_node =NewUndirectedgraphnode (cur-neighbors[i)label); Copied[curNeighbors[i]] =New_node; Copied[cur]-Neighbors.push_back (New_node); Que.push (cur-Neighbors[i]); }            }        }        returnCopied[node]; }};

This has DFS

Leetcode 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.