LeetCode 题解(22): Clone Graph

题目:

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

题解:

按BFS遍历 Old Graph,创建Map保存Old Graph到New Graph的节点的映射,每当从队列中弹出一个元素并处理其neighbor时,先在map中寻找是否已存在该邻居节点从老节点到新节点的映射,如果不存在,创建新节点,并将新节点加入new graph当前节点的邻居列表中,如果存在,直接从map中读出该节点并加入到当前节点的邻居列表中。

/**
 * 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 node;
        queue<UndirectedGraphNode*> nodeQueue;
        map<UndirectedGraphNode*, UndirectedGraphNode*> visited;
        
        UndirectedGraphNode *newRoot = new UndirectedGraphNode(node->label);
        visited[node] = newRoot;
        nodeQueue.push(node);
        while(!nodeQueue.empty())
        {
            UndirectedGraphNode *old = nodeQueue.front();
            nodeQueue.pop();
            for(auto iter: old->neighbors)
            {
                if(!visited.count(iter))
                {
                    UndirectedGraphNode *newNode = new UndirectedGraphNode(iter->label);
                    visited[old]->neighbors.push_back(newNode);
                    visited[iter] = newNode;
                    nodeQueue.push(iter);
                }
                else
                {
                    visited[old]->neighbors.push_back(visited[iter]);
                }
            }
        }
        return newRoot;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值