数学基础
The definition of a graph should just involve sets(set of vertices and set of edges).
入门题
133. Clone Graph
解题思路
因为题目已经说清楚为Connected graph, 所以我们可以先过一遍所有的点,将点进行拷贝,再将每个点的edge set进行拷贝。为防止重复拷贝以及方便寻找,用unordered_map<Node*,Node*> 记录原graph的点和复制后graph的点。
Time Complexity O(M+N) M: number of nodes, N : number of edges
Space Complexity O(M) M: number of nodes
class Solution {
unordered_map<Node*, Node*> m;
public:
Node* cloneGraph(Node* node) {
if(!node) return nullptr;
dfs(node);
for(auto [from, to]: m){
for(auto n: from->neighbors){
to->neighbors.push_back(m[n]);
}
}
return m[node];
}
void dfs(Node* node){
m[node] = new Node(node->val);
for(auto next: node->neighbors){
if(!m[next]){
dfs(next);
}
}
}
};
类似题
- 138. Copy List with Random Pointer (Medium)
- 1490. Clone N-ary Tree (Medium)
- 1485. Clone Binary Tree With Random Pointer
Clone/copy With Random Pointer 是最像的,思路一模一样。Clone N-ary Tree可以使用同样的也可以不单独列dfs function 直接callback本身copy_n->children.push_back(cloneTree(child));Time/Space Complexity 一致