133.Clone Graph:典型的なDFS

892 ワード

タイトル:
Clone an undirected graph.Each node in the graph contains a  label and a list of its  neighbors.
コード:
/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    unordered_map ht;
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if(!node) return NULL;
        if(ht.find(node) == ht.end()){
            ht[node] = new UndirectedGraphNode(node->label);
            for(auto it : node->neighbors){
                (ht[node]->neighbors).push_back(cloneGraph(it));
            }
                
        }
        return ht[node];
        
    }
};