码迷,mamicode.com
首页 > 其他好文 > 详细

Clone Graph [leetcode] dfs和bfs

时间:2014-10-09 01:23:57      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:leetcode

变量unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> cloneMap;

因为会有环,所以需要cloneMap记录旧的节点和新的节点对。

还需要一个visited记录已经访问过的节点,可以和cloneMap合并在一起。


DFS

在克隆某个Node时,首先放入map中。

之后遍历neighbors。如果neighbors不在map里,即没有访问过,则递归调用cloneGraph函数。

最后返回克隆过的节点。

    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if (node == NULL) return NULL;
        if (cloneMap.find(node) != cloneMap.end()) 
            return cloneMap[node];
        cloneMap[node] = new UndirectedGraphNode(node->label);
        cloneMap[node]->neighbors = vector<UndirectedGraphNode *>();
        for (int i = 0; i < node->neighbors.size(); i++)
        {
            UndirectedGraphNode * curNode = node->neighbors[i];
            UndirectedGraphNode * newNode = cloneGraph(curNode);
            cloneMap[node]->neighbors.push_back(newNode);
        }
        return cloneMap[node];
    }

BFS

使用一个queue记录要访问的节点。

因为不能在访问queue中节点的时候再创建对应的node==>因为在处理父亲节点的时候需同时创建好其neighbors

所以需要在将不在map中的neighbors(没有访问过的子节点)放入queue的同时创建克隆的节点,并且放入map里。

    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if (node == NULL) return NULL;
        vector<UndirectedGraphNode *> queue;
        queue.push_back(node);
        cloneMap[node] = new UndirectedGraphNode(node->label);
        cloneMap[node]->neighbors = vector<UndirectedGraphNode *>();
        
        for (int i = 0; i < queue.size(); i++)
        {
            UndirectedGraphNode * newNode = cloneMap[queue[i]];
            for (int j = 0; j < queue[i]->neighbors.size(); j++)
            {
                UndirectedGraphNode * curNb = queue[i]->neighbors[j];
                if (cloneMap.find(curNb) == cloneMap.end())
                {
                    queue.push_back(curNb);
                    UndirectedGraphNode * newNb = new UndirectedGraphNode(curNb->label);
                    newNb->neighbors = vector<UndirectedGraphNode *>();
                    cloneMap[curNb] = newNb;
                }
                newNode->neighbors.push_back(cloneMap[curNb]);
            }
        }
        return cloneMap[node];
    }


Clone Graph [leetcode] dfs和bfs

标签:leetcode

原文地址:http://blog.csdn.net/peerlessbloom/article/details/39899987

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!