[LeetCode] Clone Graph

简介: This problem is an application of graph traversal, which has two systematic methods: Bread-First Search (BFS) and Depth-First Search (DFS).

 

This problem is an application of graph traversal, which has two systematic methods: Bread-First Search (BFS) and Depth-First Search (DFS). In the following, I am going to assume that you are familiar with them and just focus on what I think is the most tricky part of this problem, that is, what else is needed beyond graph traversal to clone a graph?

In order to clone a graph, you need to have a copy of each node in the original graph. Well, you may not have too many ideas about it. Let's do an example.

Suppose we are given a graph {0, 1 # 1, 0}. We know that the graph has two nodes 0 and1 and they are connected to each other.

We now start from 0. We make a copy of 0. Then we check 0's neighbors and we see 1. We make a copy of 1 and we add the copy to the neighbors of the copy of 0. Now the cloned graph is {0 (copy), 1 (copy)}. Then we visit 1. We make a copy of 1... well, wait, why do we make another copy of it? We already have one! Note that if you make a new copy of the node, these copies are not the same and the graph structure will be wrong! This is just what I mean by "the most tricky part of this problem". In fact, we need to maintain a mapping from each node to its copy. If the node has an existed copy, we simply use it. So in the above example, the remaining process is that we visit the copy of 1 and add the copy of 0 to its neighbors and the cloned graph is eventually {0 (copy), 1 (copy) # 1 (copy), 0 (copy)}.

Note that the above process uses BFS. Of course, you can use DFS. The key is the node-copy mapping, anyway.


BFS 

 1 class Solution {
 2 public:
 3     UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
 4         if (!node) return NULL;
 5         UndirectedGraphNode* copy = new UndirectedGraphNode(node -> label);
 6         mp[node] = copy;
 7         queue<UndirectedGraphNode*> toVisit;
 8         toVisit.push(node);
 9         while (!toVisit.empty()) {
10             UndirectedGraphNode* cur = toVisit.front();
11             toVisit.pop();
12             for (int i = 0; i < (int)cur -> neighbors.size(); i++) {
13                 UndirectedGraphNode* neigh = cur -> neighbors[i];
14                 if (mp.find(neigh) == mp.end()) {
15                     UndirectedGraphNode* neigh_copy = new UndirectedGraphNode(neigh -> label);
16                     mp[neigh] = neigh_copy;
17                     toVisit.push(neigh);
18                 }
19                 mp[cur] -> neighbors.push_back(mp[neigh]);
20             }
21         }
22         return copy;
23     }
24 private:
25     unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mp;
26 };

DFS

This very succinct DFS code is taken from this post.

 1 class Solution {
 2 public:
 3     UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
 4         if (!node) return NULL;
 5         if (mp.find(node) == mp.end()) {
 6             mp[node] = new UndirectedGraphNode(node -> label);
 7             for (UndirectedGraphNode* neigh : node -> neighbors)
 8                 mp[node] -> neighbors.push_back(cloneGraph(neigh));
 9         }
10         return mp[node];
11     }
12 private:
13     unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mp;
14 };

If you want to learn more about this problem, you may refer to this article.

 

目录
相关文章
|
Python
LeetCode 133:克隆图 Clone Graph
题目: 给定无向连通图中一个节点的引用,返回该图的深拷贝(克隆)。图中的每个节点都包含它的值 val(Int) 和其邻居的列表(list[Node])。 Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph.
1025 0
[LeetCode] Graph Valid Tree
Problem Description: Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
769 0
【LeetCode从零单排】No133. clon graph (BFS广度优先搜索)
背景 (以下背景资料转载自:http://www.cnblogs.com/springfor/p/3874591.html?utm_source=tuicool) DFS(Dpeth-first Search)顾名思义,就是深度搜索,一条路走到黑,再选新的路。记得上Algorithm的时候,教授举得例子就是说,DFS很像好奇的小孩,你给这个小孩几个盒子套盒子,好奇的小孩肯定会一个盒子打开后继
1215 0
|
2月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
3月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
57 6
|
3月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
114 2
|
22天前
|
机器学习/深度学习 人工智能 自然语言处理
280页PDF,全方位评估OpenAI o1,Leetcode刷题准确率竟这么高
【10月更文挑战第24天】近年来,OpenAI的o1模型在大型语言模型(LLMs)中脱颖而出,展现出卓越的推理能力和知识整合能力。基于Transformer架构,o1模型采用了链式思维和强化学习等先进技术,显著提升了其在编程竞赛、医学影像报告生成、数学问题解决、自然语言推理和芯片设计等领域的表现。本文将全面评估o1模型的性能及其对AI研究和应用的潜在影响。
17 1
|
2月前
|
数据采集 负载均衡 安全
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口
本文提供了多个多线程编程问题的解决方案,包括设计有限阻塞队列、多线程网页爬虫、红绿灯路口等,每个问题都给出了至少一种实现方法,涵盖了互斥锁、条件变量、信号量等线程同步机制的使用。
LeetCode刷题 多线程编程九则 | 1188. 设计有限阻塞队列 1242. 多线程网页爬虫 1279. 红绿灯路口