Leetcode 133克隆图 C++

思路:图的遍历可以分别深度优先搜索和广度优先搜索两种方法。这儿采用深度优先遍历。
利用map来记录遍历的节点是否已经遍历过了,然后遍历当前节点的邻居,并加入到当前克隆节点的邻居neighbors数组中,同时对邻居调用递归函数。

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector neighbors;

    Node() {}

    Node(int _val, vector _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};
*/
class Solution {
public:
    Node* cloneGraph(Node* node) {
        unordered_map m;
        return helper(node,m);
    }
    Node*helper(Node* node,unordered_map &m)
    {
        if(!node) return NULL;
        if(m.count(node)) return m[node];
        Node* clone=new Node(node->val);
        m[node]=clone;
        for(Node* neighbor:node->neighbors)
        {
            clone->neighbors.push_back(helper(neighbor,m));
        }
        return clone;
    }
};

你可能感兴趣的:(Leetcode 133克隆图 C++)