LeetCode OJ 133: Clone Graph, leetcodeoj

Source: Internet
Author: User

LeetCode OJ 133: Clone Graph, leetcodeoj

The questions are as follows:

The question is quite long. In fact, you only need to pay attention to the first line. The idea of this question is quite obvious. For the figure, either BFS or DFS. As for the details, I think it is very similar to question 138: Copy List with Random Pointer. During the BFS or DFS process, you may need to adjust the adjacent contacts of the vertex. In this case, do not forget that its adjacent contacts may not be created yet. Therefore, we have the following ideas:

Traverse an undirected graph twice. First, create all nodes without saving the relationship between vertices. Second, adjust the relationship between vertices. The relationship between vertices is stored in neighbors. To locate the position of the newly created vertex, the one-to-one correspondence between the original vertex and the new vertex pointer needs to be saved during the first calendar, map or unordered_map can be saved here.

Here I am talking a little too long. Please see the comments in the code to understand. Here, I use BFS traversal. The time complexity is O (N), and the space complexity is O (N ).

1/** 2 * Definition for undirected graph. 3 * struct UndirectedGraphNode {4 * int label; 5 * vector <UndirectedGraphNode *> neighbors; 6 * UndirectedGraphNode (int x): label (x) {}; 7 *}; 8 */9 class Solution {10 public: 11 UndirectedGraphNode * cloneGraph (UndirectedGraphNode * node) 12 {13 if (node = NULL) 14 {15 return NULL; 16} 17 18 map <UndirectedGraphNode *, UndirectedGraphNode *> gphMap; 19 queue <U NdirectedGraphNode *> gphQue; 20 21 // create all vertices 22 gphQue. push (node); 23 while (! GphQue. empty () 24 {25 UndirectedGraphNode * tmp = gphQue. front (); 26 gphQue. pop (); 27 28 if (gphMap. find (tmp) = gphMap. end () 29 {30 UndirectedGraphNode * newNode = new UndirectedGraphNode (tmp-> label); 31 gphMap [tmp] = newNode; 32 33 for (int I = 0; I! = Tmp-> neighbors. size (); ++ I) 34 {35 gphQue. push (tmp-> neighbors [I]); 36} 37} 38} 39 40 // adjust the relationship between vertices 41 gphQue. push (node); 42 while (! GphQue. empty () 43 {44 UndirectedGraphNode * tmp = gphQue. front (); 45 gphQue. pop (); 46 47 UndirectedGraphNode * exitNode = gphMap [tmp]; 48 if (exitNode-> neighbors. empty ()&&! Tmp-> neighbors. empty () 49 {50 for (int I = 0; I! = Tmp-> neighbors. size (); ++ I) 51 {52 exitNode-> neighbors. push_back (gphMap [tmp-> neighbors [I]); 53 gphQue. push (tmp-> neighbors [I]); 54} 55} 56} 57 58 return gphMap [node]; 59} 60 };

In fact, the above method is clear and intuitive. But you still need to consider whether it can be optimized and only be traversed once. Anyway, during my interview, the interviewer said, "Just traverse once And Find Out (implement ).... In fact, it is not difficult to implement it. You only need to combine the traversal operations of the two parts. Below I will give the BFS and DFS algorithms respectively. The time complexity of the two algorithms is O (N), and the space complexity is O (N ).

The BFS Algorithm for copying images is as follows:

 1 class Solution { 2 public: 3     UndirectedGraphNode *cloneGraph(const UndirectedGraphNode *node)  4     { 5         if (node == NULL)  6         { 7             return NULL; 8         } 9 10         map<const UndirectedGraphNode*, UndirectedGraphNode*> gphMap;11         queue<const UndirectedGraphNode *> gphQue;12         13         gphQue.push(node);14         gphMap[node] = new UndirectedGraphNode(node->label);15         while (!gphQue.empty()) 16         {17             const UndirectedGraphNode *tmp = gphQue.front();18             gphQue.pop();19 20             for (int i = 0; i != tmp->neighbors.size(); ++i)21             {22                 if (gphMap.find(tmp->neighbors[i]) == gphMap.end())23                 {24                     //build the vertex25                     UndirectedGraphNode *newNode = new UndirectedGraphNode(tmp->neighbors[i]->label);26                     gphMap[tmp->neighbors[i]] = newNode;27                     gphMap[tmp]->neighbors.push_back(newNode);            //Adjust the Vertex    28                     gphQue.push(tmp->neighbors[i]);29                 }30                 else31                 {32                     gphMap[tmp]->neighbors.push_back(gphMap[tmp->neighbors[i]]);33                 }34             }35         }36 37         return gphMap[node];38     }39 };

 

The DFS Algorithm for copying images is as follows:

 1 class Solution { 2 public: 3     UndirectedGraphNode *cloneGraph(const UndirectedGraphNode *node)  4     { 5         if(node == NULL) 6         { 7             return NULL; 8         } 9     10         map<const UndirectedGraphNode*, UndirectedGraphNode*> gphMap;11         12         return GphClone(node, gphMap); //or return gphMap[node]13     }14 private:15     // DFS16     static UndirectedGraphNode* GphClone(const UndirectedGraphNode *node, 17         map<const UndirectedGraphNode*, UndirectedGraphNode*> &gphMap) 18     {19             // a copy already exists20             if (gphMap.find(node) != gphMap.end()) 21             {22                 return gphMap[node];                23             }24 25             UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label);26             gphMap[node] = newNode;27 28             for (int i = 0; i != node->neighbors.size(); ++i)29             {30                 newNode->neighbors.push_back(GphClone(node->neighbors[i], gphMap));31             }32             33             return newNode;34     }35 };

Although the time complexity is O (N), from the submission results, the DFS seems to be a little faster, this does not understand.

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.