(M)DFS:133. Clone Graph

每次搜索的时候看这个结点是不是已经被创建,是的话就返回其copy,否则就创建,然后再依次深度遍历其邻居结点并将其加入邻居集合中去

/**
 * 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;  
        if(hash.count(node))    return hash[node];
        hash[node] = new UndirectedGraphNode(node->label);
        for(auto val : node->neighbors)
            hash[node]->neighbors.push_back(cloneGraph(val));
        return hash[node];
    }
private:  
    unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> hash;  
};

还有一种解法,这道题和前面一个random list的copy的题类似,关键点是建立一个map存放旧数据结构里的节点和新数据结构里的节点的对应关系。对于这个题,我一开始觉得应该先遍历一遍图,每个节点重建,完善map结构。然后再遍历一遍,把每个节点的neighbors填好。但是其实一遍遍历就可以做完:

/**
 * 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*> m;
        queue<UndirectedGraphNode*> q;
        q.push(node);
        while(!q.empty()){
            UndirectedGraphNode *n = q.front();
            q.pop();
            if(!m[n])
            {
            	UndirectedGraphNode *newnode = new UndirectedGraphNode(n->label);
                m[n] = newnode;
            }
            
            for(auto a : n->neighbors){
                if(!m[a])
                {
                    UndirectedGraphNode *newa = new UndirectedGraphNode(a->label);
                    m[a] = newa;
                    q.push(a);
                }
                m[n]->neighbors.push_back(m[a]);
            }
        }
        return m[node];
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值