Leetcode: 133. Clone Graph(Week6, Medium)

17 篇文章 1 订阅

注:本题使用BFS算法


Leetcode 133
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
     / \
     \_/

题意:
实现一个函数以完成无向图的复制。该函数的输入是指向无向图中的某个节点的指针,该函数的输出是指向复制后的无向图中的某个节点的指针。

思路
获取到原无向图的每个节点,对每个节点进行逐一复制。

算法

  • 1.定义需要的容器
queue<int> q; // 用于存储BFS得到的图节点
map<int, UndirectedGraphNode *> new_graph; // 用于保存指向新无向图每个节点的指针 
  • 2.BFS遍历
    (1)将头结点push进队列中,并在new_graph容器中为其申请动态内存;
    (2)取队列的首部到临时变量中,然后将其pop出队列。对于每个临时变量,遍历其neighbors容器,如果容器中有未包含于new_graph中的节点先push到队列中,然后在new_graph容器中为其分配内存;
    (3)重复执行(2),直到队列为空

  • 3.返回新无向图中的某个节点。

代码如下

/*
2017/10/15  133. Clone Graph

思路:使用BFS遍历原图中所有节点,然后逐个复制。

 * 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 == NULL) return NULL;
        map<int, UndirectedGraphNode*> new_graph;
        new_graph.insert(pair<int, UndirectedGraphNode*>(node->label, new UndirectedGraphNode(node->label)));
        queue<UndirectedGraphNode*> q;
        q.push(node);
        while(!q.empty()) {
            UndirectedGraphNode* pArr = q.front();
            q.pop();
            for (int i = 0; i < (pArr->neighbors).size(); i++) {
                int label = (pArr->neighbors[i])->label;
                if (new_graph.find(label) == new_graph.end()) {
                    q.push(pArr->neighbors[i]);
                    new_graph.insert(pair<int, UndirectedGraphNode*>(label,  new UndirectedGraphNode(label)));
                }
                (new_graph[pArr->label]->neighbors).push_back(new_graph[label]);
            }
        }
        return new_graph[node->label];
    }
};

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值