Skip to content

Commit 6adbac6

Browse files
authored
added clone an undirected graph in cpp
1 parent 2b97ead commit 6adbac6

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed

C++/Clone an Undirected Graph.cpp

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
struct GraphNode
5+
{
6+
int val;
7+
vector<GraphNode*> neighbours;
8+
};
9+
10+
GraphNode *cloneGraph(GraphNode *src)
11+
{
12+
map<GraphNode*, GraphNode*> m;
13+
queue<GraphNode*> q;
14+
15+
q.push(src);
16+
GraphNode *node;
17+
18+
node = new GraphNode();
19+
node->val = src->val;
20+
21+
m[src] = node;
22+
while (!q.empty())
23+
{
24+
GraphNode *u = q.front();
25+
q.pop();
26+
vector<GraphNode *> v = u->neighbours;
27+
int n = v.size();
28+
for (int i = 0; i < n; i++)
29+
{
30+
if (m[v[i]] == NULL)
31+
{
32+
node = new GraphNode();
33+
node->val = v[i]->val;
34+
m[v[i]] = node;
35+
q.push(v[i]);
36+
}
37+
m[u]->neighbours.push_back(m[v[i]]);
38+
}
39+
}
40+
41+
return m[src];
42+
}
43+
44+
GraphNode *buildGraph()
45+
{
46+
GraphNode *node1 = new GraphNode();
47+
node1->val = 1;
48+
GraphNode *node2 = new GraphNode();
49+
node2->val = 2;
50+
GraphNode *node3 = new GraphNode();
51+
node3->val = 3;
52+
GraphNode *node4 = new GraphNode();
53+
node4->val = 4;
54+
vector<GraphNode *> v;
55+
v.push_back(node2);
56+
v.push_back(node4);
57+
node1->neighbours = v;
58+
v.clear();
59+
v.push_back(node1);
60+
v.push_back(node3);
61+
node2->neighbours = v;
62+
v.clear();
63+
v.push_back(node2);
64+
v.push_back(node4);
65+
node3->neighbours = v;
66+
v.clear();
67+
v.push_back(node3);
68+
v.push_back(node1);
69+
node4->neighbours = v;
70+
return node1;
71+
}
72+
void bfs(GraphNode *src)
73+
{
74+
map<GraphNode*, bool> visit;
75+
queue<GraphNode*> q;
76+
q.push(src);
77+
visit[src] = true;
78+
while (!q.empty())
79+
{
80+
GraphNode *u = q.front();
81+
cout << "Value of Node " << u->val << "\n";
82+
cout << "Address of Node " <<u << "\n";
83+
q.pop();
84+
vector<GraphNode *> v = u->neighbours;
85+
int n = v.size();
86+
for (int i = 0; i < n; i++)
87+
{
88+
if (!visit[v[i]])
89+
{
90+
visit[v[i]] = true;
91+
q.push(v[i]);
92+
}
93+
}
94+
}
95+
cout << endl;
96+
}
97+
98+
int main()
99+
{
100+
GraphNode *src = buildGraph();
101+
cout << "BFS Traversal before cloning\n";
102+
bfs(src);
103+
GraphNode *newsrc = cloneGraph(src);
104+
cout << "BFS Traversal after cloning\n";
105+
bfs(newsrc);
106+
return 0;
107+
}

0 commit comments

Comments
 (0)