Skip to main content

133. Clone Graph

Hint

/*
// Definition for a Node.
class Node {
public:
int val; // Value of the node
vector<Node*> neighbors; // List of neighbors (adjacent nodes)

Node() {
val = 0;
neighbors = vector<Node*>();
}

Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}

Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/

class Solution {
private:
// Map to store the mapping between original nodes and their clones
public:
Node* cloneGraph(Node* node)
{
// If the input node is null, return null

// If the node has already been cloned, return its clone

// Create a new clone for the current node

// Recursively clone all the neighbors of the current node
for ()
{
// Add the cloned neighbor to the current node's clone's neighbor list
}
// Return the clone of the current node
}
};
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/

class Solution {
private:
unordered_map<Node*, Node*> m;
public:
Node* cloneGraph(Node* node)
{
if (!node) return nullptr;
if (m.count(node)) return m[node];

m[node] = new Node(node->val);

for (auto& nei : node->neighbors)
{
m[node]->neighbors.push_back(cloneGraph(nei));
}
return m[node];
}
};
  • T: O(V+E)O(V + E)
  • S: O(V)O(V)