clone-graph

1. clone-graph

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

思路:dfs,其实就是递归。

 1 /**
 2  * Definition for undirected graph.
 3  * struct UndirectedGraphNode {
 4  *     int label;
 5  *     vector<UndirectedGraphNode *> neighbors;
 6  *     UndirectedGraphNode(int x) : label(x) {};
 7  * };
 8  */
 9 class Solution {
10 public:
11     unordered_map<UndirectedGraphNode *,UndirectedGraphNode *> hash;
12     UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
13         if(!node)return node;
14         if(hash.find(node)==hash.end()){
15             hash[node] = new UndirectedGraphNode(node->label);
16             for(auto x : node->neighbors){
17                 (hash[node]->neighbors).push_back(cloneGraph(x));
18             }
19         }
20         return hash[node];
21     }
22 };
原文地址:https://www.cnblogs.com/xctcherry/p/8783482.html