133. Clone Graph 复制无向图

133. Clone Graph 复制无向图_第1张图片
image.png

bfs

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if(!node) return NULL;
        map hashmap;
        UndirectedGraphNode * p2 = new UndirectedGraphNode(node->label);
        queue q;
        q.push(node);
        hashmap[node] = p2;
        while(!q.empty()){
            UndirectedGraphNode * cur = q.front();
            q.pop();
            p2 = hashmap[cur];
            for(int i = 0; i < cur->neighbors.size(); i++){
                UndirectedGraphNode * nb= cur->neighbors[i];
                if(hashmap.count(nb)) p2->neighbors.push_back(hashmap[nb]);
                else{
                    UndirectedGraphNode * tmp = new UndirectedGraphNode(nb->label);
                    hashmap[nb] = tmp;
                    p2->neighbors.push_back(hashmap[nb]);
                    q.push(nb);//要注意这里q的元素,是原图中的元素
                }
            }
        }
        return hashmap[node];
    }
};

dfs

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if(!node) return NULL;
        map hashmap;
        UndirectedGraphNode * p2 = new UndirectedGraphNode(node->label);
        stack q;
        q.push(node);
        hashmap[node] = p2;
        while(!q.empty()){
            UndirectedGraphNode * cur = q.top();
            q.pop();
            p2 = hashmap[cur];
            for(int i = 0; i < cur->neighbors.size(); i++){
                UndirectedGraphNode * nb= cur->neighbors[i];
                if(hashmap.count(nb)) p2->neighbors.push_back(hashmap[nb]);
                else{
                    UndirectedGraphNode * tmp = new UndirectedGraphNode(nb->label);
                    hashmap[nb] = tmp;
                    p2->neighbors.push_back(hashmap[nb]);
                    q.push(nb);//要注意这里q的元素,是原图中的元素
                }
            }
        }
        return hashmap[node];
    }
};

你可能感兴趣的:(133. Clone Graph 复制无向图)