【算法】clone a graph


http://leetcode.com/2012/05/clone-graph-part-i.html


Clone a graph. Input is a Node pointer. Return the Node pointer of the cloned graph.

A graph is defined below:
struct Node {
vector neighbors;


这种gragh的表示方式只能表示连通图。有很多种类型的图用过这种表示方式都表示不了,该问题只针对这种数据结构能表示的图。

需要根据输入,遍历图。方法:深度优先或广度优先


广度优先:用一个队列保存节点,每次弹出一个节点,就再将这个节点的neighbours放入队列中,直到队列为空。同时还要用一个hashmap来保存已经访问过的节点,防止出现无限循环。在hashmap中出现过的节点,不再拷贝,也不再放入队列中。

代码:

typedef unordered_map<Node *, Node *> Map;
 
Node *clone(Node *graph) {
    if (!graph) return NULL;
 
    Map map;
    queue<Node *> q;
    q.push(graph);
 
    Node *graphCopy = new Node();
    map[graph] = graphCopy;
 
    while (!q.empty()) {
        Node *node = q.front();
        q.pop();
        int n = node->neighbors.size();
        for (int i = 0; i < n; i++) {
            Node *neighbor = node->neighbors[i];
            // no copy exists
            if (map.find(neighbor) == map.end()) {
                Node *p = new Node();
                map[node]->neighbors.push_back(p);
                map[neighbor] = p;
                q.push(neighbor);
            } else {     // a copy already exists
                map[node]->neighbors.push_back(map[neighbor]);
            }
        }
    }
 
    return graphCopy;
}

深度优先遍历,递归调用:

Node* DFS(Node *Input, hash_map &hm){

if(hm.find(Input) != hm.end()){
return hm[Input];
}
Node *output = new Node();
hm[Input] = output;
for(int i = 0; i next.size();i++){
output->next.push_back(DFS(Input->next[i],hm));
}
return output;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值