美文网首页
133. Clone Graph 复制无向图

133. Clone Graph 复制无向图

作者: 刘小小gogo | 来源:发表于2018-09-23 18:08 被阅读0次
    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];
        }
    };
    

    相关文章

      网友评论

          本文标题:133. Clone Graph 复制无向图

          本文链接:https://www.haomeiwen.com/subject/tldqoftx.html