【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 ...
随机推荐
- java静态代码分析工具infer
infer是一个静态代码分析工具,探测bugs. 主要支持Java.C/C++ 安装:brew install infer 在线展示:https://codeboard.io/projects/115 ...
- maven选包算法(两个相同的包)
引入了两个相同groupId和artifactId的jar,但是版本不同,选择层级最浅的包,层级可以通过依赖树来看
- EF操作增删改查
lianxiEntities db = new lianxiEntities();//上下文的入口 #region //EF Added //UserInfo user = new UserInfo( ...
- Spring Security OAuth2 Demo
Spring Security OAuth2 Demo 项目使用的是MySql存储, 需要先创建以下表结构: CREATE SCHEMA IF NOT EXISTS `alan-oauth` DEFA ...
- 说说CSS样式中你不知道的“大于号”
继承在一定程度上让程序在编写的过程中更加方便,但是有时候也会给我们的程序带来一定的困扰,所以认真的学习继承的原理,以及处理的方法很重要.下面是Css中处理继承的一个方法.在一段CSS代码中见到一个大于 ...
- JavaScript数组与字符串常用方法总结
先来一段代码引子: var str='hello world'; alert(str.charAt());//通过下标查找值: alert(str.indexOf());//通过值查找字符串下标:没有 ...
- WebClient.DownloadData突然失灵
有如下的代码: try { byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = we ...
- iOS UIApplication的代理方法总结
1.简单介绍 1> 整个应用程序的象征,一个应用程序就一个UIApplication对象.使用了单例设计模式 2> 通过[UIApplication sharedApplication]訪 ...
- Thrift 文件的格式及可用的数据类型
编写thrift文件是,须要知道thrift文件支持的数据类型有哪些.假设定义Service等.以下是官方文档的说明: # # Thrift Tutorial # Mark Slee (mcslee@ ...
- 从servlet中获取spring的WebApplicationContext
需要做一个参数初始化类,当web应用被加载时从数据库里取出相关的参数设置 ,并把这些参数放置到application里,jsp页面可以从中取出. 1.在web.xml中配置: <servlet& ...