LintCode 137. Clone Graph

  1. 需要掌握图的表示方法,图分为两种常见表示:邻接表,邻接矩阵。主要有一个neighbors的vector来存所有邻居的信息
  2. 遇到图的题,要遍历图,一般选择BFS,因为宽度优先遍历可以用队列实现,不会发生栈溢出的情况
  3. 遇到图的题,要遍历图,需要一个Hashmap,因为图可能有环,尤其对于无向图,为了避免二次访问,Hashmap非常重要
  4. 需要记忆,c++中Hashmap用unordered_map来表示
  5. 需要记忆,mapping.find(x) == mapping.end()来判断是否已存储了某值
  6. 克隆图,便是遍历一遍,生成点和边,注意可以一遍生成没必要遍历两遍。每次while都是生成neighbors的点和front的之间的边。
/**
 * 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) {
        if (node == NULL) {
            return NULL;
        }
        
        queue<UndirectedGraphNode *> q;
        q.push(node);
        unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> mapping;
        mapping[node] = new UndirectedGraphNode(node->label);
        
        while (!q.empty()) {
            UndirectedGraphNode * head = q.front();
            q.pop();
            for (UndirectedGraphNode * neighbor: head->neighbors) {
                if (mapping.find(neighbor) == mapping.end()) {
                    mapping[neighbor] = new UndirectedGraphNode(neighbor->label);
                    q.push(neighbor);
                }
                mapping[head]->neighbors.push_back(mapping[neighbor]);
            }
        }
        return mapping[node];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值