Leetcode: 133. Clone Graph(Week6, Medium)

注:本题使用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];
    }
};

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

点赞