# Clone Graph Part I | Nicksxs's Blog
problemClone a graph. Input is a Node pointer. Return the Node pointer of the cloned graph. A graph is defined below: struct Node &#123; vector neighbors; &#125;

# Nicksxs's Blog

What hurts more, the pain of hard work or the pain of regret?

0%

# Clone Graph Part I

发表于 2014-12-30 分类于 leetcode 阅读次数： 阅读次数： Disqus：

### problem

    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;
    }

### code

    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;
    }

### anlysis

using the Breadth-first traversal
and use a map to save the neighbors not to be duplicated.

相关文章

- Leetcode 234 回文链表(Palindrome Linked List) 题解分析
- G1收集器概述
- 34_Search_for_a_Range
- add-two-number
- Leetcode 021 合并两个有序链表 ( Merge Two Sorted Lists ) 题解分析