-
Notifications
You must be signed in to change notification settings - Fork 0
/
Clone an Undirected Graph.cpp
63 lines (55 loc) · 1.47 KB
/
Clone an Undirected Graph.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// DFS
class Solution {
public:
Node* help(Node* node,vector<Node*>& visited)
{
Node* graph=new Node(node->val);
visited[node->val]=graph;
for(auto it:node->neighbors)
{
if(!visited[it->val])
help(it,visited);
graph->neighbors.push_back(visited[it->val]);
}
return graph;
}
Node* cloneGraph(Node* node) {
vector<Node*> visited(10001,NULL);
return help(node,visited);
}
};
//BFS
class Solution {
public:
Node* cloneGraph(Node* node) {
vector<Node*> visited(10001,NULL);
queue<pair<Node*,Node*>> q;
Node* start=NULL;
q.push({node,NULL});
while(!q.empty())
{
Node* n=q.front().first;
Node* clone=q.front().second;
q.pop();
Node* graph=NULL;
if(clone==NULL)
graph=new Node(n->val);
else
graph=clone;
if(start==NULL)
start=graph;
visited[n->val]=graph;
for(auto it:n->neighbors)
{
if(visited[it->val]==0)
{
Node* newnode=new Node(it->val);
q.push({it,newnode});
visited[it->val]=newnode;
}
graph->neighbors.push_back(visited[it->val]);
}
}
return start;
}
};