1. 程式人生 > >[LeetCode] Clone Graph 無向圖的複製

[LeetCode] Clone Graph 無向圖的複製

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


OJ's undirected graph serialization:

Nodes are 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 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to 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
         / \
         \_/

這道無向圖的複製問題和之前的拷貝帶有隨機指標的連結串列有些類似,那道題的難點是如何處理每個節點的隨機指標,這道題目的難點在於如何處理每個節點的neighbors,由於在深度拷貝每一個節點後,還要將其所有neighbors放到一個vector中,而如何避免重複拷貝呢?這道題好就好在所有節點值不同,所以我們可以使用雜湊表來對應節點值和新生成的節點。對於圖的遍歷的兩大基本方法是深度優先搜尋DFS和廣度優先搜尋BFS,此題的兩種解法可參見網友

愛做飯的小瑩子的部落格,這裡我們使用深度優先搜尋DFS來解答此題,程式碼如下:

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        unordered_map<int, UndirectedGraphNode*> umap;
        return clone(node, umap);
    }
    UndirectedGraphNode *clone(UndirectedGraphNode *node, unordered_map<int, UndirectedGraphNode*> &umap) {
        if (!node) return node;
        if (umap.count(node->label)) return umap[node->label];
        UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label);
        umap[node->label] = newNode;
        for (int i = 0; i < node->neighbors.size(); ++i) {
            (newNode->neighbors).push_back(clone(node->neighbors[i], umap));
        }
        return newNode;
    } 
};