题目大意
克隆一个无向图
解题思路
此题听闻某位大神说过好像是google的一次白板面试题,之前做过一个克隆链表的题目,是先遍历一次链表然后建立节点(建立map,原图节点作为key,克隆图节点作为value),第二次遍历再连线,所以这里亦可以依法炮制,先深度遍历原图建立起相应的节点,然后第二次深度遍历将边连接起来。当然,如果代码能力够纯熟,可以深搜的同时连边,这样代码会更加紧凑,但是逻辑方面就略难理清楚,就题目数据,单纯从复杂度上来说差别不是特别大。
总结
题目不难,主要就是细节,细节!!
代码
1、先生成节点,第二遍遍历连边
class Solution {
public:
map<UndirectedGraphNode*, UndirectedGraphNode*> mp;
map<UndirectedGraphNode*, bool> visited;
void createNew(UndirectedGraphNode *node){
if (mp.find(node) == mp.end()){
UndirectedGraphNode *tmp = new UndirectedGraphNode(node->label) ;
mp[node] = tmp;
vector<UndirectedGraphNode*>::iterator it;
for (it = node->neighbors.begin(); it != node->neighbors.end(); it ++){
createNew(*it);
}
}
}
void dfs(UndirectedGraphNode *node){
if (visited.find(node) == visited.end()){
visited[node] = true;
vector<UndirectedGraphNode*>::iterator it;
for (it = node->neighbors.begin(); it != node->neighbors.end(); it ++){
mp[node]->neighbors.push_back(mp[*it]);
dfs(*it);
}
}
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == NULL)return NULL;
mp.clear();
visited.clear();
UndirectedGraphNode *tmp = node;
createNew(tmp);
dfs(tmp);
return mp[node];
}
};
2、一边生成节点一边连接边(附测试样例)
#include<iostream>
#include<set>
#include<vector>
#include<map>
using namespace std;
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
map<UndirectedGraphNode*, UndirectedGraphNode*> mp;
void createNew(UndirectedGraphNode *node, UndirectedGraphNode *©){//建立新的节点
if (mp.find(node) == mp.end()){
copy = new UndirectedGraphNode(node->label);
mp[node] = copy;
}
else {
copy = mp[node];
}
vector<UndirectedGraphNode*>::iterator it;
if (copy->neighbors.empty()){//判断当前节点是否已经走过
for (it = node->neighbors.begin(); it != node->neighbors.end(); it ++){
copy->neighbors.push_back(0);//占一个坑
createNew(*it,copy->neighbors.back());
}
}
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == NULL)return NULL;
mp.clear();
UndirectedGraphNode *copy;
createNew(node,copy);
//dfs(tmp);
return mp[node];
}
void print_dfs(UndirectedGraphNode *node){
if (visited1.find(node) == visited1.end()){
cout<<(node)->label<<endl;
visited1[node] = true;
vector<UndirectedGraphNode*>::iterator it;
for (it = node->neighbors.begin(); it != node->neighbors.end(); it ++){
print_dfs(*it);
}
}
}
int main()
{
while (cin >> n){
map<int, UndirectedGraphNode*> mpp;
for (int i = 0; i < n; i ++){
int a;
cin >> a;
UndirectedGraphNode* tmp = new UndirectedGraphNode(a);
mpp[a] = tmp;
}
cin >> n;
for (int i = 0; i < n; i ++){
int a, b;
cin >> a>>b;
mpp[a]->neighbors.push_back(mpp[b]);
mpp[b]->neighbors.push_back(mpp[a]);
}
UndirectedGraphNode* new_node = cloneGraph(mpp[1]);
print_dfs(new_node);
}
return 0;
}
/*
2
1 -1
2
1 -1
1 1
*/