Clone Graph

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.

OJ's undirected graph serialization:

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 #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (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)——无向无环图复制的更多相关文章

  1. 【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 ...

  2. 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 ...

  3. 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 ...

  4. 133. Clone Graph

    题目: Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. ...

  5. 133. Clone Graph(图的复制)

    Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph contains ...

  6. 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 ...

  7. 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 ...

  8. 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 ...

  9. [LeetCode] 133. Clone Graph 克隆无向图

    Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's ...

随机推荐

  1. chromedriver 下载

    https://sites.google.com/a/chromium.org/chromedriver/downloads   百度网盘链接:https://pan.baidu.com/s/1nwL ...

  2. Appium解锁九宫格(TouchAction)

    TouchAction 1.源码可以在这个路径找到:Lib\site-packages\appium\webdriver\common\touch_action.py class TouchActio ...

  3. (总结)CentOS Linux使用crontab运行定时任务详解

    安装crontab:yum install crontabs 说明:/sbin/service crond start //启动服务/sbin/service crond stop //关闭服务/sb ...

  4. Flutter 发布APK时,release版本和debug版本的默认权限不同

    Flutter 发布APK时,release版本和debug版本的默认权限不同 @author ixenos 在调试模式下,默认情况下启用服务扩展和多个权限(在flutter中) 当您处于发布模式时, ...

  5. DefaultActionInvocation 源码

    /** * Copyright 2002-2006,2009 The Apache Software Foundation. * * Licensed under the Apache License ...

  6. 命令行-s的意思

    -s,signal,意思就是信号,一般是发送信号. 如: # 关闭 nginx -s stop;

  7. iOS开发工具篇-AppStore统计工具

    苹果官方的iTunes Connect提供的销售数据统计功能比较弱,例如只能保存最近30天的详细销售数据,界面丑陋, 无法查看App的排名历史变化情况等. 早有一些公司提供了专门的解决方案或工具.这些 ...

  8. P1122 最大子树和 (树形DP)

    题目描述 小明对数学饱有兴趣,并且是个勤奋好学的学生,总是在课后留在教室向老师请教一些问题.一天他早晨骑车去上课,路上见到一个老伯正在修剪花花草草,顿时想到了一个有关修剪花卉的问题.于是当日课后,小明 ...

  9. ElasticSearch索引自定义类型

    ES可以自动检测字段并设置映射类型.如果设置的索引类型不是我们所需要的,我们可以自行定义. Rest API设置自定义索引 首先通过ES自动映射一个IP地址的字段的类型: <pre name=& ...

  10. eq=等于gt=大于lt=小于的英文全称

    EQ: Equal GT: Greater Than LT: Less than 知道全称就不会忘记