【LEETCODE OJ】Clone Graph
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的更多相关文章
- 【LeetCode OJ】Interleaving String
Problem Link: http://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 ...
- 【LeetCode OJ】Reverse Words in a String
Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...
- 【LeetCode OJ】Palindrome Partitioning
Problem Link: http://oj.leetcode.com/problems/palindrome-partitioning/ We solve this problem using D ...
- 【LeetCode OJ】Word Break II
Problem link: http://oj.leetcode.com/problems/word-break-ii/ This problem is some extension of the w ...
- 【LeetCode OJ】Validate Binary Search Tree
Problem Link: https://oj.leetcode.com/problems/validate-binary-search-tree/ We inorder-traverse the ...
- 【LeetCode OJ】Recover Binary Search Tree
Problem Link: https://oj.leetcode.com/problems/recover-binary-search-tree/ We know that the inorder ...
- 【LeetCode OJ】Same Tree
Problem Link: https://oj.leetcode.com/problems/same-tree/ The following recursive version is accepte ...
- 【LeetCode OJ】Symmetric Tree
Problem Link: https://oj.leetcode.com/problems/symmetric-tree/ To solve the problem, we can traverse ...
- 【LeetCode OJ】Binary Tree Level Order Traversal
Problem Link: https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ Traverse the tree ...
随机推荐
- 51nod 1613翻硬币
题目链接:51nod 1613 翻硬币 知乎上的理论解法http://www.zhihu.com/question/26570175/answer/33312310 本题精髓在于奇偶性讨论. 若 n ...
- ThoughtWorks微服务架构交流心得
ThoughtWorks微服务架构交流心得: (1)<人月神话>中谈到软件开发没有银弹,根源在于软件所解决的领域问题本身固有的复杂性,微服务正是从领域问题角度上进行服务拆分,来降低软件 ...
- Windows Store App 应用程序存储空间
与上面介绍的三种不同应用程序数据存储类型对应,应用程序有三种数据存储空间,分别为本地应用程序数据存储空间.漫游应用程序数据存储空间和临时应用程序数据存储空间.通过使用ApplicationData类的 ...
- Ubuntu 13.10 Broadcom BCM4313问题
开始找不到无线网卡,后来不知道怎么就出来了,但是速度很慢.用下面的方法解决的(我也不知道哪条命令起的作用,反正现在正常了): sudo apt-get remove --purge bcmwl-ker ...
- 一些qml资料
qml开发ios应用 http://www.seanyxie.com/qt-qml%E7%A7%BB%E5%8A%A8%E5%BC%80%E5%8F%91%E4%B9%8B%E5%9C%A8ios%E ...
- C#重启系统代码
C#重启窗体代码 System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location ...
- autoLyout纯代码适配
前言 1 MagicNumber -> autoresizingMask -> autolayout 以上是纯手写代码所经历的关于页面布局的三个时期 在iphone1-iphone3gs时 ...
- bzoj 2143: 飞飞侠
#include<cstdio> #include<iostream> #include<queue> #define inf 1000000000 #define ...
- ASP.NET MVC过滤器(一)
MVC过滤器是加在 Controller 或 Action 上的一种 Attribute,通过过滤器,MVC 网站在处理用户请求时,可以处理一些附加的操作,如:用户权限验证.系统日志.异常处理.缓存等 ...
- Validform自定义提示效果-使用自定义弹出框
$(function(){ $.Tipmsg.r=null; $("#add").Validform({ tiptype:function(msg){ layer.msg(msg) ...