LeetCode 133. Clone Graph
LeetCode 133. Clone Graph
LINK: https://leetcode.com/problems/clone-graph/
Matter
You are given a reference to a node in an undirected graph.
Create a deep copy of the entire graph and return the cloned node corresponding to the input.
Each node contains a value and a list of its neighbors.
Example.
[1]
Input:
adjList = [[2,4],[1,3],[2,4],[1,3]]
Output:
[[2,4],[1,3],[2,4],[1,3]]
Explanation:
Each node and its neighbors are duplicated to form an identical graph structure.
[2]
Input:
adjList = [[]]
Output:
[[]]
Explanation:
A single node with no neighbors.
[3]
Input:
adjList = []
Output:
[]
Explanation:
An empty graph.
Constraints
0 <= number of nodes <= 100
1 <= Node.val <= 100
Node values are unique
No duplicate edges and no self-loops
Problem analysis
This is a graph traversal + cloning problem.
The key difficulty is Avoid duplicating the same node multiple times
Since the graph may contain cycles, we must track already cloned nodes.
- Use a hashmap to store mapping:
1
original_node → cloned_node
Solution
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
#include <iostream>
#include <vector>
#include <functional>
#include <unordered_map>
class Node {
public:
int val;
std::vector<Node*> neighbors;
Node() {
val = 0;
neighbors = std::vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = std::vector<Node*>();
}
Node(int _val, std::vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
class Solution {
public:
Node* cloneGraph(Node* node)
{
std::function<Node*(Node*)> lmdClone = [&](Node* nodeOrg) -> Node*
{
Node* nodeClone = nullptr;
do
{
if(visited.find(nodeOrg) != visited.end())
{
nodeClone = visited[nodeOrg];
break;
}
nodeClone = new Node(nodeOrg->val);
nodeClone->neighbors.resize(nodeOrg->neighbors.size(), nullptr);
visited[nodeOrg] = nodeClone;
for(int i =0; i < nodeOrg->neighbors.size(); ++i)
{
if (nodeOrg->neighbors[i] == nullptr)
nodeClone->neighbors[i] = nullptr;
else
nodeClone->neighbors[i] = lmdClone(nodeOrg->neighbors[i]);
}
}
while (false);
return nodeClone;
};
Node* nodeResult = nullptr;
do
{
if (node == nullptr)
break;
nodeResult = lmdClone(node);
}
while (false);
return nodeResult;
}
public:
std::unordered_map<Node*, Node*> visited;
};