【LeetCode】133. Clone Graph (3 solutions)
Clone Graph
Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
Nodes are labeled uniquely.
We use #
as a separator for each node, and ,
as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}
.
The graph has a total of three nodes, and therefore contains three parts as separated by #
.
- First node is labeled as
0
. Connect node0
to both nodes1
and2
. - Second node is labeled as
1
. Connect node1
to node2
. - Third node is labeled as
2
. Connect node2
to node2
(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
这题只需一边遍历一遍复制就可以了。
因此至少可以用三种方法:
1、广度优先遍历(BFS)
2、深度优先遍历(DFS)
2.1、递归
2.2、非递归
解法一:广度优先遍历
变量说明:
映射表m用来保存原图结点与克隆结点的对应关系。
映射表visited用来记录已经访问过的原图结点,防止循环访问。
队列q用于记录广度优先遍历的层次信息。
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == NULL)
return NULL;
// map from origin node to copy node
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> m;
unordered_map<UndirectedGraphNode *, bool> visited;
queue<UndirectedGraphNode*> q;
q.push(node);
while(!q.empty())
{// BFS
UndirectedGraphNode* front = q.front();
q.pop(); if(visited[front] == false)
{
visited[front] = true; UndirectedGraphNode* cur;
if(m.find(front) == m.end())
{
cur = new UndirectedGraphNode(front->label);
m[front] = cur;
}
else
{
cur = m[front];
}
for(int i = ; i < front->neighbors.size(); i ++)
{
if(m.find(front->neighbors[i]) == m.end())
{
UndirectedGraphNode* nei = new UndirectedGraphNode(front->neighbors[i]->label);
m[front->neighbors[i]] = nei;
cur->neighbors.push_back(nei); q.push(front->neighbors[i]);
}
else
{
cur->neighbors.push_back(m[front->neighbors[i]]);
}
}
}
}
return m[node];
}
};
解法二:递归深度优先遍历(DFS)
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
map<UndirectedGraphNode *, UndirectedGraphNode *> m; UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node)
{
if(node == NULL)
return NULL; if(m.find(node) != m.end()) //if node is visited, just return the recorded nodeClone
return m[node]; UndirectedGraphNode *nodeClone = new UndirectedGraphNode(node->label);
m[node] = nodeClone;
for(int st = ; st < node->neighbors.size(); st ++)
{
UndirectedGraphNode *temp = cloneGraph(node->neighbors[st]);
if(temp != NULL)
nodeClone->neighbors.push_back(temp);
}
return nodeClone;
}
};
解法三:非递归深度优先遍历(DFS)
深度优先遍历需要进行邻居计数。如果邻居已经全部访问,则该节点访问完成,可以出栈,否则就要继续处理下一个邻居。
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/ struct Node
{
UndirectedGraphNode *node;
int ind; //next neighbor to visit
Node(UndirectedGraphNode *n, int i): node(n), ind(i) {}
}; class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == NULL)
return NULL;
// map from origin node to copy node
unordered_map<UndirectedGraphNode *, UndirectedGraphNode *> m;
unordered_map<UndirectedGraphNode *, bool> visited;
stack<Node*> stk;
Node* newnode = new Node(node, );
stk.push(newnode);
visited[newnode->node] = true;
while(!stk.empty())
{// DFS
Node* top = stk.top();
UndirectedGraphNode* topCopy;
if(m.find(top->node) == m.end())
{
topCopy = new UndirectedGraphNode(top->node->label);
m[top->node] = topCopy;
}
else
topCopy = m[top->node]; if(top->ind == top->node->neighbors.size())
//finished copying its neighbors
stk.pop();
else
{
while(top->ind < top->node->neighbors.size())
{
if(m.find(top->node->neighbors[top->ind]) == m.end())
{
UndirectedGraphNode* neiCopy = new UndirectedGraphNode(top->node->neighbors[top->ind]->label);
m[top->node->neighbors[top->ind]] = neiCopy;
topCopy->neighbors.push_back(neiCopy);
if(visited[top->node->neighbors[top->ind]] == false)
{
visited[top->node->neighbors[top->ind]] = true;
Node* topnei = new Node(top->node->neighbors[top->ind], );
stk.push(topnei);
}
top->ind ++;
break;
}
else
{
topCopy->neighbors.push_back(m[top->node->neighbors[top->ind]]);
top->ind ++;
}
}
}
}
return m[node];
}
};
【LeetCode】133. Clone Graph (3 solutions)的更多相关文章
- 【LeetCode】133. Clone Graph 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...
- 【leetcode】133. Clone Graph
题目如下: Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph con ...
- 【LeetCode】785. Is Graph Bipartite? 解题报告(Python)
[LeetCode]785. Is Graph Bipartite? 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu. ...
- 133. Clone Graph (3 solutions)——无向无环图复制
Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its nei ...
- 【LeetCode】75. Sort Colors (3 solutions)
Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects of t ...
- 【LeetCode】90. Subsets II (2 solutions)
Subsets II Given a collection of integers that might contain duplicates, S, return all possible subs ...
- 【Lintcode】137.Clone Graph
题目: Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. ...
- 【LeetCode】207. Course Schedule (2 solutions)
Course Schedule There are a total of n courses you have to take, labeled from 0 to n - 1. Some cours ...
- 【LeetCode】44. Wildcard Matching (2 solutions)
Wildcard Matching Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any ...
随机推荐
- MIR Flickr 1M 图像数据集(点击即可下载)
Index of /mirflickr/mirflickr1m Name Last modified Size Description Parent Directory - exif.zip ...
- 如何利用启明星Portal门户系统的Page模块构建工作流表单
启明星门户网站的Pages模块支持构建自定义表单系统.这使得对于使用表单收集用户数据的需求来说非常有用. 本文介绍如何构建一个简单的“出差系统”. 1.在页面里增加Pages模块,建立人事部部门,然后 ...
- Cesium教程系列汇总【转】
Cesium系列目录: 演示实例 ExamplesforCesium 最近老实有一些人问我,下载后在本地无法运行,我也不能保证每次都搭个环境看是否可行,或许Cesium升级版本后真有问题呢,索性在gi ...
- Android组件之Service浅谈
Service是Android中的四大组件之一,和windows中的服务是类似,服务一般没有用户操作界面,它运行于系统中不容易被用户发觉,可以使用它开发如监控之类的程序Service,手机中有的程序的 ...
- (算法)前K大的和
题目: 1.有两个数组A和B,每个数组有k个数,从两个数组中各取一个数加起来可以组成k*k个和,求这些和中的前k大. 2.有N个数组,每个数组有k个数,从N个数组中各取一个数加起来可以组成k^N个和, ...
- Discuz常见大问题-如何在自定义页面使用首页四格
根据要求把majianjun文件夹放到指定目录 在DIY模式下点击保存后面的小按钮,然后导入XML文件 默认是采集所有版块的数据,你可以保存之后再次DIY,然后设置数据来源和设置标题等信息. 需要注意 ...
- HTTP和Socket的区别
1: HTTP协议即超文本传送协议(Hypertext Transfer Protocol ),是Web联网的基础,也是手机联网常用的协议之一,HTTP协议是建立在TCP协议之上的一种应用. HTTP ...
- Oracle体系结构二(学习笔记)
- 1z0-052 q209_6
6: You executed this command to create a temporary table: SQL> CREATE GLOBAL TEMPORARY TABLE repo ...
- JqGrid获得所有选中行数据ID数组,获取所有行的ID数组
获得选中行的ID数组:var ids = $("jqgridtableid").jqGrid('getGridParam','selarrrow'); 获得所有行的ID数组:var ...