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];
}
};
转自:http://www.cnblogs.com/ganganloveu/p/4119462.html
133. Clone Graph (3 solutions)——无向无环图复制的更多相关文章
- 【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 nei ...
- 133. Clone Graph 138. Copy List with Random Pointer 拷贝图和链表
133. Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of it ...
- leetcode 133. Clone Graph ----- java
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...
- 133. Clone Graph
题目: Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. ...
- 133. Clone Graph(图的复制)
Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph contains ...
- 133. Clone Graph (Graph, Map; DFS)
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...
- Graph 133. Clone Graph in three ways(bfs, dfs, bfs(recursive))
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...
- Java for LeetCode 133 Clone Graph
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...
- [LeetCode] 133. Clone Graph 克隆无向图
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...
随机推荐
- Python面向对象(成员)(二)
1. 成员 在类中你能写的所有内容都是类的成员 2. 变量 1. 实例变量: 由对象去访问的变量. class Person: def __init__(self, name, id, gender, ...
- LeetCode(91) Decode Ways
题目 A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A ...
- 《C/C++专项练习》— (1)
前言 每每到了一周之计的Monday啊,精神总是不佳,写篇博客提提神儿吧~ 继上次完成<C/C++工程师综合练习卷>后,有事儿没事儿就想刷几道题,赶脚不错,巩固了不少基础知识呢,要坚持哦~ ...
- ZZULIoj 1913: 小火山的计算能力
Description 别人说小火山的计算能力不行,小火山很生气,于是他想证明自己,现在有一个表达式,他想计算出来. Input 首先是一个t(1<=20)表示测试组数.然后一个表达式,表达式长 ...
- visionPro工业视觉工具中英文一览表
- Scrapy应用之抓取《宦海沉浮》小说
目标站点 http://www.shushu8.com/huanhaichenfu/ 第一步:新建项目 KeysdeMacBook:Desktop keys$ scrapy startprojec ...
- 【SQL Server】SQL常用系统函数
SQL常用系统函数 函数类型 函数表达式 功能 应用举例 字符串函数 SubString(表达式,起始,长度) 取子串 SubString('ABCDEFG',3,4) Right(表达式,长度) 右 ...
- TOJ 2017: N-Credible Mazes
2017: N-Credible Mazes Time Limit(Common/Java):1000MS/10000MS Memory Limit:65536KByteTotal Subm ...
- 算法复习——迭代加深搜索(骑士精神bzoj1085)
题目: Description 在一个5×5的棋盘上有12个白色的骑士和12个黑色的骑士, 且有一个空位.在任何时候一个骑士都能按照骑士的走法(它可以走到和它横坐标相差为1,纵坐标相差为2或者横坐标相 ...
- ftp链接、上传、下载、断开
开发环境:Jdk 1.8 引入第三方库:commons-net-2.2.jar(针对第一种方法) 一.基于第三方库FtpClient的FTP服务器数据传输 由于是基于第三方库,所以这里基本上没有太多要 ...