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);
    }
};
全部评论

相关推荐

蚂蚁 基架java (n+6)*16 签字费若干
点赞 评论 收藏
分享
头像
11-06 10:58
已编辑
门头沟学院 嵌入式工程师
双非25想找富婆不想打工:哦,这该死的伦敦腔,我敢打赌,你简直是个天才,如果我有offer的话,我一定用offer狠狠的打在你的脸上
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务