-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclonegraph.cpp
More file actions
113 lines (89 loc) · 2.64 KB
/
clonegraph.cpp
File metadata and controls
113 lines (89 loc) · 2.64 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <iostream>
using namespace std;
class Node {
public:
int val;
Node** neighbors;
int neighborCount;
Node(int _val) {
val = _val;
neighbors = new Node*[101]; // support up to 100 neighbors
neighborCount = 0;
}
~Node() {
delete[] neighbors;
}
};
class Solution {
public:
Node* visited[101]; // array to map node val -> cloned node pointer
Solution() {
for (int i = 0; i <= 100; i++) {
visited[i] = NULL;
}
}
Node* cloneGraph(Node* node) {
if (node == NULL) return NULL;
if (visited[node->val] != NULL) {
return visited[node->val];
}
// Create clone
Node* cloneNode = new Node(node->val);
visited[node->val] = cloneNode;
// Recursively clone neighbors
for (int i = 0; i < node->neighborCount; i++) {
Node* neighbor = node->neighbors[i];
Node* clonedNeighbor = cloneGraph(neighbor);
cloneNode->neighbors[cloneNode->neighborCount++] = clonedNeighbor;
}
return cloneNode;
}
};
void printGraph(Node* node, bool* printed) {
if (node == NULL || printed[node->val]) return;
printed[node->val] = true;
cout << "Node " << node->val << " is connected to: ";
for (int i = 0; i < node->neighborCount; i++) {
cout << node->neighbors[i]->val << " ";
}
cout << endl;
for (int i = 0; i < node->neighborCount; i++) {
printGraph(node->neighbors[i], printed);
}
}
int main() {
// Create a small graph: 1--2, 1--3, 2--4
Node* node1 = new Node(1);
Node* node2 = new Node(2);
Node* node3 = new Node(3);
Node* node4 = new Node(4);
node1->neighbors[node1->neighborCount++] = node2;
node1->neighbors[node1->neighborCount++] = node3;
node2->neighbors[node2->neighborCount++] = node1;
node2->neighbors[node2->neighborCount++] = node4;
node3->neighbors[node3->neighborCount++] = node1;
node4->neighbors[node4->neighborCount++] = node2;
// Print original graph
bool printedOriginal[101] = {false};
cout << "Original Graph:\n";
printGraph(node1, printedOriginal);
// Clone the graph
Solution sol;
Node* cloned = sol.cloneGraph(node1);
// Print cloned graph
bool printedClone[101] = {false};
cout << "\nCloned Graph:\n";
printGraph(cloned, printedClone);
// Clean up original graph
delete node1;
delete node2;
delete node3;
delete node4;
// Clean up cloned graph
for (int i = 1; i <= 100; i++) {
if (sol.visited[i] != NULL) {
delete sol.visited[i];
}
}
return 0;
}