【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 ...
随机推荐
- Qt之坐标系统
简述 坐标系统是由QPainter类控制的,再加上QPaintDevice和QPaintEngine类,就形成了Qt的绘图体系. QPainter:用于执行绘图操作. QPaintDevice:二维空 ...
- (30)odoo中的快捷标签
* 快捷标签 提供快捷标签是为了简化代码的编码,把复杂的工作封装化 * 找到封装化的源码: openerp/tools/convert.py xml_import self._ ...
- MyBatis执行过程显示SQL语句的log4j配置
log4j.properties文件 log4j.rootLogger=debug,stdout,logfile log4j.appender.stdout=org.apache.log4j.Co ...
- Search for a Range [LeetCode]
Given a sorted array of integers, find the starting and ending position of a given target value. You ...
- 数据库索引<二> 补充前篇
你要准备的软件有: 最新版 Rsync for windows 服务端:cwRsync_Server_2.1.5_Installer.zip 客户端:cwRsync_2.1.5_Installer.z ...
- Asp.Net 导出Excel数据文件
表格例子如下: <table id="tableExcel" width="100%" border="1" cellspacing= ...
- (转)mysql的增删改查
MySQL数据库的增删改查. 1,首先启动mysql数据库的服务,在运行的窗口中输入:net start mysql,这样,就可 以启动mysql数据库的服务,同理,输入net stop mysql, ...
- BroadcastReceiver的实例----基于Service的音乐播放器之一
下面的程序开发了一个基于Service的音乐盒,程序的音乐将会由后台运行的Service组件负责播放,当后台的播放状态发生改变时,程序将会通过发送广播通知前台Activity更新界面:当用户单击前台A ...
- 安卓/res/menu/的使用
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http:/ ...
- pandas进行数据分析需要的一些操作
一.查看数据 1.查看DataFrame前xx行或后xx行a=DataFrame(data);a.head(6)表示显示前6行数据,若head()中不带参数则会显示全部数据.a.tail(6)表示显示 ...