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. CentOS 7.x安装配置

    简述 VMware可以创建多个虚拟机,每个虚拟机上都可以安装各种类型的操作系统.安装方法也有很多种.下面,主要以ISO镜像安装为例,介绍CentOS 7.x的安装过程及相关的参数设置. 简述 创建虚拟 ...

  2. getsockname和getpeername

    int getsockname(int sockfd, struct sockaddr *localaddr, socklen_t *addrlen);  // 获取与某个套接字关联的本地协议地址 i ...

  3. hdu----(1671)Phone List(Trie带标签)

    Phone List Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  4. jQuery 2.0.3 源码分析 Deferrred概念

    转载http://www.cnblogs.com/aaronjs/p/3348569.html JavaScript编程几乎总是伴随着异步操作,传统的异步操作会在操作完成之后,使用回调函数传回结果,而 ...

  5. A-Making the Grade(POJ 3666)

    Making the Grade Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 4656   Accepted: 2206 ...

  6. c# form的设定

    1. 窗体的显示位置startPosition CenterScreen 窗体在当前居中 CenterParent 窗体在其父窗体居中 WindowDefaultBounds 窗体定期在windows ...

  7. TokuDB介绍——本质是分形树(一个叶子4MB)+缓存减少写操作

    其性能特点见:http://www.cnblogs.com/billyxp/p/3567421.html TokuDB 是一个高性能.支持事务处理的 MySQL 和 MariaDB 的存储引擎.Tok ...

  8. [转]C#综合揭秘——细说进程、应用程序域与上下文之间的关系

    引言 本文主要是介绍进程(Process).应用程序域(AppDomain)..NET上下文(Context)的概念与操作.虽然在一般的开发当中这三者并不常用,但熟悉三者的关系,深入了解其作用,对提高 ...

  9. 一般处理文件.ashx中使用文件session遇到的问题

    在给其他网站提供接口的时候用ashx做的,在文件调用cs中的方法,方法中的Session报错:System.NullReferenceException: 未将对象引用设置到对象的实例. /// &l ...

  10. Div层的展开与收缩的代码

    <html> <head> <title>div展开收缩代码</title> <style> * { margin:0; padding:0 ...