Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2014-07-28 11:49  Tonix  阅读(130)  评论(0编辑  收藏  举报