1. 程式人生 > >Leetcode 133. Clone Graph

Leetcode 133. Clone Graph

133. Clone Graph

題目

Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph contains a label (int) and a list (List[UndirectedGraphNode]) of its neighbors. There is an edge between the given node and each of the nodes in its neighbors.

OJ’s undirected graph serialization (so you can understand error output):

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

Note: The information about the tree serialization is only meant so that you can understand error output if you get a wrong answer. You don’t need to understand the serialization to solve the problem.

解題思路

遍歷原圖,遇到未遍歷過的節點時,複製一個新節點。保持該節點在原圖中的關係與新節點在新圖中的關係相對應,將新節點加入新圖中。為了在新圖中快速找到與原圖中相應的節點,可以用一個 unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> dict儲存對應的節點。

方法一:BFS

(1)如果原圖頭節點為空,則返回NULL;

(2)先複製一個原圖的頭節點,加入dict中,作為新圖的頭節點;

(3)建立一個佇列,將原圖頭節點加入佇列;

(4)直到佇列未空,進行如下迴圈:取出隊首節點(該節點為原圖遍歷到的節點,而dict[隊首節點]則是新圖與該節點對應的節點),對於該節點的每個子節點,若dict中沒有對應節點(dict[子節點]不存在),則說明該節點之前未遍歷到,則複製一個該子節點,加入dict中,並將該子節點加入佇列中,將dict[子節點]加入到新圖中與隊首節點對應的節點的位元組點列表中。

(5)在第(3)步中,迴圈結束後,原圖每個節點都經歷過BFS,每遍歷到一個新節點,都會複製一個節點加入新圖中,並且維持新圖中節點的相鄰關係,因此(3)步驟結束後,新圖便是原圖的複製。將新圖中對應的頭節點dict[原圖頭節點]返回即可。

程式碼如下:

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if(!node) return NULL;
        unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> dict;
        queue<UndirectedGraphNode*> q;
        q.push(node); 
        dict[node] = new UndirectedGraphNode(node->label);
        
        while(!q.empty()){
            UndirectedGraphNode* cur = q.front(); 
            q.pop();
            for( auto next: cur->neighbors){
                if( dict.find(next) == dict.end()){
                    dict[next] = new UndirectedGraphNode(next->label);
                    q.push(next);    
                }
                dict[cur]->neighbors.push_back(dict[next]);
            }
        }
        return dict[node];
    }
    
};

方法二:DFS

(1)如果原圖頭節點為空,則返回NULL;

(2)建立一個新的dict,以原圖頭節點為引數呼叫dfs遞迴函式,該函式引數有一個節點,返回一個從該節點開始深度優先拷貝原圖後的圖的首節點。

(3)進行如下遞迴:如果dict中有對應引數node的節點,則直接返回dict[node]是,否則建立node的拷貝節點,加入dict中,對於node的每個子節點,用子節點呼叫dfs函式後返回的是從子節點開始深度優先拷貝原圖後的圖的首節點,將每個位元組點呼叫dfs後返回的節點加入dict[node]的子節點列表中,則dict[node]則是從node開始深度優先拷貝原圖後的圖的首節點,將dict[node]返回。

(4)用原圖頭節點呼叫dfs函式後返回的即是拷貝原圖後的圖的首節點。

程式碼如下:

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if(!node) return NULL;
        unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> dict;
        return dfs(dict, node);
    }

    UndirectedGraphNode* dfs(unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> &dict, UndirectedGraphNode* node){
        if( dict.find(node) != dict.end()) return dict[node];
        dict[node] = new UndirectedGraphNode(node->label);
        for( auto next: node->neighbors)
            dict[node]->neighbors.push_back(dfs(dict, next));
        return dict[node];
    }
};