【重点!DFS/记忆化递归 + BFS】LeetCode 133. Clone Graph

LeetCode 133. Clone Graph

Solution1:
DFS/记忆化递归,参考网址:http://www.cnblogs.com/grandyang/p/4267628.html
真是一道记忆化递归的好题啊~

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

private:
    UndirectedGraphNode *clone(UndirectedGraphNode *node, 
                               unordered_map<int, UndirectedGraphNode*> &umap) {
        if (!node) return node;//是针对node == NULL的情况的
        if (umap.count(node->label)) return umap[node->label];
        UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label);
        umap[node->label] = newNode;
        for (int i = 0; i < node->neighbors.size(); ++i) {
            (newNode->neighbors).push_back(clone(node->neighbors[i], umap));
        }
        return newNode;
    } 
};

Solution2:
BFS,先记录一下自己的错代码。。。
参考网址:https://blog.csdn.net/windylai123/article/details/78134293

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution { //记忆化的BFS
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if (!node) return NULL;
        原图和新图节点一一对应
        unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> node_map;
        UndirectedGraphNode *clone_node = 
            new UndirectedGraphNode(node->label);//首先克隆第一个结点
        node_map[node] = clone_node; 建立map对应
        //建一个队列,把头结点push进去
        queue<UndirectedGraphNode *> node_queue;
        node_queue.push(node);

        while (!node_queue.empty()) {
            UndirectedGraphNode *begin = node_queue.front();
            node_queue.pop();
            vector<UndirectedGraphNode *> temp = begin->neighbors;
            for (int i = 0; i < temp.size(); i++) {
                /*如果当前节点不在map里,则要生成新节点并放入队列*/ 
                if (!node_map.count(temp[i])) {
                    UndirectedGraphNode * temp_node = 
                        new UndirectedGraphNode(temp[i]->label);
                    node_map[temp[i]] = temp_node;
                    node_queue.push(temp[i]);
                }
                //生成当前节点的邻接节点
                node_map[begin]->neighbors.push_back(node_map[temp[i]]);
            }
        }
        return clone_node;
    } 
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值