LeetCode: 133. Clone Graph

LeetCode: 133. Clone Graph

题目描述

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

OJ’s undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

       1
      / \      /   \     0 --- 2
         / \          \_/

解题思路 —— 递归分治

记录复制过的,正在复制的节点, 递归地处理每一个没有处理过的节点。

AC代码

/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */
class Solution {
public:
    UndirectedGraphNode *cloneGraphRef(UndirectedGraphNode *node,
                                       map<int, UndirectedGraphNode*>& recordedNode) {

        if(node == nullptr) return nullptr;
        if(recordedNode.find(node->label) != recordedNode.end()) 
        {
            return recordedNode[node->label]; // 已经处理过, 直接返回存储的值
        }

        UndirectedGraphNode* pCurNode = new UndirectedGraphNode(node->label);
        // 记录当前的节点
        recordedNode[pCurNode->label] = pCurNode;

        // 分治:分别处理每一个 neighbors 节点
        for(size_t i = 0; i < node->neighbors.size(); ++i)
        {
            pCurNode->neighbors.push_back(cloneGraphRef(node->neighbors[i], recordedNode));
        }

        return pCurNode;
    }

    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        map<int, UndirectedGraphNode*> recordedNode;
        return cloneGraphRef(node, recordedNode);
    }
};
全部评论

相关推荐

星辰再现:裁员给校招生腾地方
点赞 评论 收藏
分享
LemontreeN:有的兄弟有的我今天一天面了五场,4个二面一个hr面
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-29 17:30
找实习找着找着就要进入7月了,马上秋招也要开始了,找实习还有意义吗?
绝迹的星:有面就面, 没面上就当日薪4位数大佬免费培训, 面上了再考虑要不要实习
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务