此题的答案非常简洁巧妙,看似用的是BFS,实则为DFS。
使用一个Map来记录克隆的旧新节点关系,然后设计一个函数,参数为node,表明这个函数要克隆node节点及其邻居关系。如果邻居就在Map里,直接返回,因为这是一个已经克隆过的邻居,否则,递归地克隆其邻居。
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
map<UndirectedGraphNode *, UndirectedGraphNode *> myMap;
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
return cloneNode(node);
}
UndirectedGraphNode *cloneNode(UndirectedGraphNode *node) {
if (node == NULL)
return NULL;
if (myMap.find(node) != myMap.end())
return myMap[node];
UndirectedGraphNode *t = new UndirectedGraphNode(node->label);
myMap[node] = t;
for (int i = 0; i < (node->neighbors).size(); ++i) {
t->neighbors.push_back(cloneNode((node->neighbors)[i]));
}
return t;
}
};
http://oj.leetcode.com/problems/clone-graph/