#137 Clone Graph

本文介绍了一种使用广度优先搜索(BFS)实现无向图深拷贝的方法。通过维护一个节点映射表来避免重复创建已存在的节点,确保深拷贝后的图结构与原图完全一致。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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

How we serialize an undirected graph:

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 node2.
  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
     / \
     \_/
Example

return a deep copied graph.

题目思路:

既然是graph的deep copy,那么用bfs就可以了。需要注意的是,如果在bfs的过程中node已经存在,那么直接link上这个node就可以了,重复new node会导致最后的graph中有重复node出现。为了避免这个问题,这里用了一个map去记录所有已经new出来的nodes,如果找到的neighbor刚好在map中存在,那么直接link上就行。

Mycode(AC = 114ms):

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    /**
     * @param node: A undirected graph node
     * @return: A undirected graph node
     */
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        // write your code here
        if (node == NULL) return NULL;
        
        queue<UndirectedGraphNode *> snode;
        snode.push(node);
        
        UndirectedGraphNode *root = new UndirectedGraphNode(node->label);
        queue<UndirectedGraphNode *> scopy;
        scopy.push(root);
        
        map<int, UndirectedGraphNode *> helper;
        helper[root->label] = root;
        
        while (!snode.empty()) {
            UndirectedGraphNode *n = snode.front();
            snode.pop();
            
            UndirectedGraphNode *tmp_n = scopy.front();
            scopy.pop();
            
            for (int i = 0; i < n->neighbors.size(); i++) {
                // if node already exist, then just link the node
                if (helper.find(n->neighbors[i]->label) != helper.end()) {
                    UndirectedGraphNode *neighbor = helper[n->neighbors[i]->label];
                    tmp_n->neighbors.push_back(neighbor);
                }
                else {
                    // if node doesn't exist, then create the node, and 
                    // push the node into queue
                    UndirectedGraphNode *neighbor = new UndirectedGraphNode(n->neighbors[i]->label);
                    tmp_n->neighbors.push_back(neighbor);
                    helper[neighbor->label] = neighbor;
                    scopy.push(neighbor);
                    snode.push(n->neighbors[i]);
                }
            }
        }
        
        return root;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值