1. clone-graph
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
思路: dfs, 其实就是递归.
- /**
- * Definition for undirected graph.
- * struct UndirectedGraphNode {
- * int label;
- * vector<UndirectedGraphNode *> neighbors;
- * UndirectedGraphNode(int x) : label(x) {};
- * };
- */
- class Solution {
- public:
- unordered_map<UndirectedGraphNode *,UndirectedGraphNode *> hash;
- UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
- if(!node)return node;
- if(hash.find(node)==hash.end()){
- hash[node] = new UndirectedGraphNode(node->label);
- for(auto x : node->neighbors){
- (hash[node]->neighbors).push_back(cloneGraph(x));
- }
- }
- return hash[node];
- }
- };
- clone-graph
来源: http://www.bubuko.com/infodetail-2557658.html