http://leetcode.com/2012/05/clone-graph-part-i.html
Clone a graph. Input is a Node pointer. Return the Node pointer of the cloned graph.
A graph is defined below:
struct Node {
vector neighbors;
这种gragh的表示方式只能表示连通图。有很多种类型的图用过这种表示方式都表示不了,该问题只针对这种数据结构能表示的图。
需要根据输入,遍历图。方法:深度优先或广度优先
广度优先:用一个队列保存节点,每次弹出一个节点,就再将这个节点的neighbours放入队列中,直到队列为空。同时还要用一个hashmap来保存已经访问过的节点,防止出现无限循环。在hashmap中出现过的节点,不再拷贝,也不再放入队列中。
代码:
typedef unordered_map<Node *, Node *> Map;
Node *clone(Node *graph) {
if (!graph) return NULL;
Map map;
queue<Node *> q;
q.push(graph);
Node *graphCopy = new Node();
map[graph] = graphCopy;
while (!q.empty()) {
Node *node = q.front();
q.pop();
int n = node->neighbors.size();
for (int i = 0; i < n; i++) {
Node *neighbor = node->neighbors[i];
// no copy exists
if (map.find(neighbor) == map.end()) {
Node *p = new Node();
map[node]->neighbors.push_back(p);
map[neighbor] = p;
q.push(neighbor);
} else { // a copy already exists
map[node]->neighbors.push_back(map[neighbor]);
}
}
}
return graphCopy;
}
深度优先遍历,递归调用:
Node* DFS(Node *Input, hash_map &hm){
if(hm.find(Input) != hm.end()){
return hm[Input];
}
Node *output = new Node();
hm[Input] = output;
for(int i = 0; i next.size();i++){
output->next.push_back(DFS(Input->next[i],hm));
}
return output;
}