Problem link:

http://oj.leetcode.com/problems/clone-graph/

This problem is very similar to "Copy List with Random Pointer", we need a hash map to map a node and its clone.

The algorithm is 2-pass procedure as follows.

CLONE-GRAPH(GraphNode node):
Let MAP be a hash map with pairs of (key=GraphNode, value=GraphNode)
Let Q be an empty queue
if node == NULL
return NULL
// BFS the graph
Q.push(node)
while Q is not empty
n = Q.pop()
Duplicate n as m
MAP[n] = m
for each nn in n's neighbor
if not MAP.haskey(nn)
Q.push(nn)
// Set the neigbors of clone nodes
for each key n in MAP
m = MAP[n]
for each nn in n's neighbor
mm = MAP[nn]
add mm into m's neighbors
// return the clone of node
return MAP[node]

However, I implemented the algorithm in python but got LTE in oj.leetcode. Then, I implemented it in C++ and accepted successfully.

The C++ code is as follows.

/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
#include <map>
#include <queue> using namespace std; class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
// Special case:
if (node == NULL) return NULL; // Declarations
map<UndirectedGraphNode*, UndirectedGraphNode*> M;
queue<UndirectedGraphNode*> Q;
UndirectedGraphNode* n = NULL; // BFS from the given node
Q.push(node);
while (! Q.empty()) {
// Pop a node in the queue a n
n = Q.front(); Q.pop();
// Clone and map n
M[n] = new UndirectedGraphNode(n->label);
// Check n's neighbors
for(vector<UndirectedGraphNode*>::iterator iter=n->neighbors.begin(); iter != n->neighbors.end(); ++iter) {
if (M.find(*iter) == M.end()) { // Not found, means not visited yet
Q.push(*iter);
}
}
} // Set neighbors of new created nodes
for(map<UndirectedGraphNode*, UndirectedGraphNode*>::iterator iter = M.begin(); iter != M.end(); ++iter) {
// iter->first: the pointer to the original node
// iter->second: the pointer to the clone
for(vector<UndirectedGraphNode*>::iterator ni = iter->first->neighbors.begin(); ni != iter->first->neighbors.end(); ++ni)
iter->second->neighbors.push_back(M[*ni]);
}
return M[node];
}
};

FYI, I also post my python version here even it is not accepted due to LTE# Definition for a undirected graph node

# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = [] class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
"""
Similar to the previous problem "Copy List with Random Pointer"
which deepcopies a list node containing (value, next, random).
So we can use similar technique.
We need to assume that each node has a path to the given node
"""
# Special case:
if node is None:
return None # We use a dictionary to map between the original node and its copy
# Also, we can use mapping.keys() to keep track the nodes we already visited
mapping = {} # BFS from the given node
q = [node]
while q:
# I do not pop/push on q, since it is not efficient for python build-in list structure
# Instead, I just create a new empty list, and iterate all elements in q.
# After adding all neighbors to new_q, set q = new_q
new_q = []
for n in q:
# Clone n and map it with its clone
mapping[n] = UndirectedGraphNode(n.label)
# Check its neighbors
for x in n.neighbors:
if x not in mapping.keys():
new_q.append(x)
q = new_q # All nodes are mapping.keys()
for n in mapping.keys():
for x in n.neighbors:
mapping[n].neighbors.append(mapping[x]) # Return the clone of node
return mapping[node]

  

【LEETCODE OJ】Clone Graph的更多相关文章

  1. 【LeetCode OJ】Interleaving String

    Problem Link: http://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 ...

  2. 【LeetCode OJ】Reverse Words in a String

    Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...

  3. 【LeetCode OJ】Palindrome Partitioning

    Problem Link: http://oj.leetcode.com/problems/palindrome-partitioning/ We solve this problem using D ...

  4. 【LeetCode OJ】Word Break II

    Problem link: http://oj.leetcode.com/problems/word-break-ii/ This problem is some extension of the w ...

  5. 【LeetCode OJ】Validate Binary Search Tree

    Problem Link: https://oj.leetcode.com/problems/validate-binary-search-tree/ We inorder-traverse the ...

  6. 【LeetCode OJ】Recover Binary Search Tree

    Problem Link: https://oj.leetcode.com/problems/recover-binary-search-tree/ We know that the inorder ...

  7. 【LeetCode OJ】Same Tree

    Problem Link: https://oj.leetcode.com/problems/same-tree/ The following recursive version is accepte ...

  8. 【LeetCode OJ】Symmetric Tree

    Problem Link: https://oj.leetcode.com/problems/symmetric-tree/ To solve the problem, we can traverse ...

  9. 【LeetCode OJ】Binary Tree Level Order Traversal

    Problem Link: https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ Traverse the tree ...

随机推荐

  1. MyEclipse自动补全与快捷键设置

    一般默认情况下,Eclipse ,MyEclipse的代码提示功能是比Microsoft Visual Studio的差很多的,主要是Eclipse ,MyEclipse本身有很多选项是默认关闭的,要 ...

  2. placehold.it-在线图片生成器(转载)

    做网站的时候 如果 有的产品等客户没有上传图片,可以用这个网站生成的图片 并配以文字进行图片的占位 以免造成页面的空挡或者页面错位等 原文地址:http://www.cnblogs.com/xumen ...

  3. 阮一峰:RSA算法原理(一)

    今天看到一篇好文章,关于加密算法,收藏了觉得不过瘾,还是自己贴一遍,也能加深一下印象. 原文链接:http://www.ruanyifeng.com/blog/2013/06/rsa_algorith ...

  4. JavaScript第一部分

    一.JavaScript简介 1.JavaScript是个什么东西? 它是个脚本语言,需要有宿主文件,它的宿主文件是HTML文件. 2.它与Java什么关系? 没有什么直接的联系,Java是Sun公司 ...

  5. VS2005保存文件很慢

    VS2005出了点毛病,边的出奇的慢,简直不可忍受. 症状是:保存文件很慢,哪怕是修改一个变量,也要等上大概20秒 保存文件的时候,VS2005会在局域网内寻找一个主机当这个主机不在线的时候vs200 ...

  6. 本地调试WordPress计划终告失败

    小猪本来想把博客的网站数据迁移到自己的电脑上面,mysql数据库还是放在主机供应商,这样就能缓解一下每次写博客时访问速度捉急的状况. 计划是美满的,但是只到实施的时候才发现各种问题.先是直接运行程序时 ...

  7. Android为ViewPager增加切换动画——使用属性动画.

    ViewPager作为Android最常用的的组件之一,相信大家在项目中会频繁的使用到的,例如利用ViewPager制作引导页.轮播图,甚至做整个app的表现层的框架等等. Android3.0以下不 ...

  8. ASP.NET的运行原理与运行机制

    在Asp.net4和4.5中,新增了WebPages Framework,编写页面代码使用了新的Razor语法,代码更加的简洁和符合Web标准,编写方式更接近于PHP和以前的Asp,和使用WebFor ...

  9. 各种主流数据库的比较(所以说我觉得Oracle这个keng?入的不错?)

    随着计算机技术不断发展,各种数据库编程工具也随着发展,使当今的大多数程序开发人员可以摆脱枯燥无味的用计算机指令或汇编语言开发软件,而是利用一系列高效的.具有良好可视化的编程工具去开发各种数据库软件,从 ...

  10. ARM安装ROS- indigo

    Ubuntu ARM install of ROS Indigo 溪西创客小屋 There are currently builds of ROS for Ubuntu Trusty armhf. T ...