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. javascript常用函数(1):jquery操作select 基本操作

    $(this).children('option:selected').val();//这就是selected的值 $("#charCity").empty();//内容清空: j ...

  2. hdu----(4686)Arc of Dream(矩阵快速幂)

    Arc of Dream Time Limit: 2000/2000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)Tota ...

  3. win7_64bit下桌面及开始菜单中图标变为.lnk

    以下内容参考整理与MSDN: 1.首先 win+r 2.打开运行程序 3.输入: regedit 4.找到: 计算机\HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\WIND ...

  4. BZOJ1737 [Usaco2005 jan]Naptime 午睡时间

    断环然后裸DP就好了... $f[i][j][k]$表示1号时间段没有被算入答案,到了第$i$个时间段,一共选了$j$个时间段,$k = 0 /1$表示第i个时间段有没有被算进答案的最优值 $g[i] ...

  5. jQuery修改后代、兄弟样式

    <div> <div >1</div> <div class="one"> 2 <div>2_1 <div> ...

  6. 一步一步配置NLB

    废话不说,配置NLB需要准备以下环境: 1. 至少两个服务器,我的是windows server 2008 R2; 我的两个服务器名分别为NLB3和NLB2,其中NLB3是主,为什么呢?后面会谈到,在 ...

  7. 基于Storm的工程中使用log4j

    最近使用Storm开发,发现log4j死活打不出debug级别的日志,网上搜到的关于log4j配置的方法都试过了,均无效. 最终发现问题是这样的:最新的storm使用的日志系统已经从log4j切换到了 ...

  8. 重点关注之Filter的使用(性能计数和错误处理)

    Web API中的filter与MVC中的filter非常类似,最主要的不同是,MVC中的filter放在命名空间System.Web.Mvc下,而Web API中的filter则放在命名空间Syst ...

  9. 转: Jsp9个内置对象详解

    1.request对象 客户端的请求信息被封装在request对象中,通过它才能了解到客户的需求, 然后做出响应.它是HttpServletRequest类的实例. 序号方法说明 objectgetA ...

  10. 使用ASP.Net WebAPI构建REST服务(六)——Self-Host

    Asp.Net WebAPI生成的是一个程序集,并不是独立的进程,因此,要运行的时候必须将其承载在相应的宿主上,一般比较常见的是IIS承载.很多时候,我们为了简化部署或者功能集成,需要将其承载到独立的 ...