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

LeetCode "Clone Graph"

时间:2014-07-28 15:07:53      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   div   new   leetcode   

A BFS usage.

class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if (!node) return NULL;

        UndirectedGraphNode *pRet = NULL;

        queue<UndirectedGraphNode*> q;
        unordered_map<int, UndirectedGraphNode *> map;
        
        q.push(node);        
        while (!q.empty())
        {
            UndirectedGraphNode *p = q.front();
            //    Create new node
            UndirectedGraphNode *pNew = NULL;
            if (map.find(p->label) == map.end())
            {
                pNew = new UndirectedGraphNode(p->label);
                map[p->label] = pNew;
                if (!pRet)    pRet = pNew;
            }
            else
            {
                pNew = map[p->label];
            }

            for (UndirectedGraphNode *pC : p->neighbors)
            {
                UndirectedGraphNode *pNewC = NULL;
                if (map.find(pC->label) == map.end())
                {
                    pNewC = new UndirectedGraphNode(pC->label);
                    map[pC->label] = pNewC;
                    q.push(pC);
                }
                else
                {
                    pNewC = map[pC->label];
                }
                pNew->neighbors.push_back(pNewC);                
            }
            q.pop();
        }
        return pRet;
    }
};

LeetCode "Clone Graph",布布扣,bubuko.com

LeetCode "Clone Graph"

标签:style   blog   color   io   for   div   new   leetcode   

原文地址:http://www.cnblogs.com/tonix/p/3872804.html

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