133. Clone Graph 复制无向图

image.png

bfs

/**
 * 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;
        map<UndirectedGraphNode *, UndirectedGraphNode *> hashmap;
        UndirectedGraphNode * p2 = new UndirectedGraphNode(node->label);
        queue<UndirectedGraphNode *> 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<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if(!node) return NULL;
        map<UndirectedGraphNode *, UndirectedGraphNode *> hashmap;
        UndirectedGraphNode * p2 = new UndirectedGraphNode(node->label);
        stack<UndirectedGraphNode *> 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];
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容