首页 > 代码库 > Graph Clone(DFS)

Graph Clone(DFS)

    果然用了map记录key和value之后代码量少了很多,出错几率也变少了,不到一个小时就写完了~~~上完代码继续做下一题!大声笑

  

class Solution {private:    unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> umap;public:// 用DFS// 用map来存储,key是旧的结点地址,value是新的结点地址// 第一遍,如果没有访问过,就clone并加入umap// 第二遍,如果没有访问过,就clone他的neighbors    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {        if(node == NULL) return NULL;        DFS(node);        DFSNei(node);        return umap[node];           }    void DFS(UndirectedGraphNode *node){        umap[node] = new UndirectedGraphNode(node->label); // 访问node        for(auto nei: node->neighbors){ // 访问与Node相邻的            if(umap.count(nei) == 0){ // 如果没有访问过                DFS(nei);            }        }    }    void DFSNei(UndirectedGraphNode *node){        for(auto nei: node->neighbors){ // clone umap[node]的neighbors            umap[node]->neighbors.push_back(umap[nei]);        }        for(auto nei: node->neighbors){            if(!nei->neighbors.empty() && umap[nei]->neighbors.empty()){               DFSNei(nei);            }        }    }};

    刚又看了大神的代码。。。。又被完爆了。。。破碎的心。。哎。。。还需加油啊!书呆子

Graph Clone(DFS)