标签:style blog http color io ar for sp div
果然用了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); } } } };
刚又看了大神的代码。。。。又被完爆了。。。。。哎。。。还需加油啊!
标签:style blog http color io ar for sp div
原文地址:http://www.cnblogs.com/skysand/p/4038488.html