写在前面的话:

  看了看自己的博客,从一月底开始就没怎么更新过,我也确实将近5个月没怎么写代码了。今天突然觉得有些心慌,感觉手都已经生疏了。果然,随便找了道题就卡住了。隐约感觉要用map但又不太记得用法了,知道可以用DFS或BFS却又理不清思路。费了两个小时,结果写了一个shit一样的代码才通过。唉好忧伤啊。

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
/ \
\_/

我的解法:

反应了好久,才发现题目的难点是防止结点的重复建立。我的方法没有用map,很繁琐。

#include<iostream>
#include<vector>
#include<algorithm>
#include<stdlib.h>
using namespace std; struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
class Solution {
public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
//获取所有独立的结点
vector<UndirectedGraphNode *> UniqueNodes;
getUniqueNodes(node, UniqueNodes); return findNode(node, UniqueNodes);
} //查找指定结点并返回
UndirectedGraphNode * findNode(UndirectedGraphNode * node, vector<UndirectedGraphNode *> UniqueNodes)
{
if(NULL == node)
return NULL;
for(int i = ; i < UniqueNodes.size(); i++)
{
if(node->label == UniqueNodes[i]->label)
{
return UniqueNodes[i];
}
}
return NULL;
} //获取图中所有的结点和连接信息
void getUniqueNodes(UndirectedGraphNode *node, vector<UndirectedGraphNode *>& UniqueNodes)
{
//结点空或已存在时直接返回
if(NULL == node || NULL != findNode(node, UniqueNodes))
return; //存储新出现的结点
UndirectedGraphNode * newNode = new UndirectedGraphNode(node->label);
UniqueNodes.push_back(newNode);
for(int i = ; i < node->neighbors.size(); i++)
{
getUniqueNodes(node->neighbors[i], UniqueNodes);
newNode->neighbors.push_back(findNode(node->neighbors[i], UniqueNodes));
}
}
}; int main()
{
Solution s; UndirectedGraphNode * node0 = new UndirectedGraphNode();
UndirectedGraphNode * node1 = new UndirectedGraphNode();
UndirectedGraphNode * node2 = new UndirectedGraphNode();
node0->neighbors.push_back(node1);
node0->neighbors.push_back(node2);
node1->neighbors.push_back(node2);
node2->neighbors.push_back(node2); UndirectedGraphNode * newNode = s.cloneGraph(node0);
return ;
}

网上大神解法

/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
private:
unordered_map<UndirectedGraphNode*,UndirectedGraphNode*> hash;
public:
//BFS
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(!node) return NULL;
queue<UndirectedGraphNode*> Qu;
Qu.push(node);
hash[node] = new UndirectedGraphNode(node->label);
while(!Qu.empty()){
UndirectedGraphNode * tmp = Qu.front();
Qu.pop();
for(UndirectedGraphNode * neighbor : tmp->neighbors){
if(hash.find(neighbor) == hash.end()){
hash[neighbor] = new UndirectedGraphNode(neighbor->label);
Qu.push(neighbor);
}
hash[tmp]->neighbors.push_back(hash[neighbor]);
}
}
return hash[node];
}
//DFS
UndirectedGraphNode *cloneGraph1(UndirectedGraphNode *node) {
if(!node) return NULL;
if(hash.find(node) == hash.end()){
hash[node] = new UndirectedGraphNode(node->label);
for(UndirectedGraphNode* neighbor : node->neighbors){
hash[node]->neighbors.push_back(cloneGraph1(neighbor));
}
}
return hash[node];
}
};

【leetcode】clone-graph的更多相关文章

  1. 【leetcode】Clone Graph(python)

    类似于二叉树的三种遍历,我们能够基于遍历的模板做非常多额外的事情,图的两种遍历,深度和广度模板相同也能够做非常多额外的事情,这里举例利用深度优先遍历的模板来进行复制,深度优先中,我们先訪问第一个结点, ...

  2. 【LeetCode】图论 graph(共20题)

    [133]Clone Graph (2019年3月9日,复习) 给定一个图,返回它的深拷贝. 题解:dfs 或者 bfs 都可以 /* // Definition for a Node. class ...

  3. 【LeetCode】BFS(共43题)

    [101]Symmetric Tree 判断一棵树是不是对称. 题解:直接递归判断了,感觉和bfs没有什么强联系,当然如果你一定要用queue改写的话,勉强也能算bfs. // 这个题目的重点是 比较 ...

  4. 【LeetCode】深搜DFS(共85题)

    [98]Validate Binary Search Tree [99]Recover Binary Search Tree [100]Same Tree [101]Symmetric Tree [1 ...

  5. 【LeetCode】785. Is Graph Bipartite? 解题报告(Python)

    [LeetCode]785. Is Graph Bipartite? 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu. ...

  6. 【LeetCode】代码模板,刷题必会

    目录 二分查找 排序的写法 BFS的写法 DFS的写法 回溯法 树 递归 迭代 前序遍历 中序遍历 后序遍历 构建完全二叉树 并查集 前缀树 图遍历 Dijkstra算法 Floyd-Warshall ...

  7. 【LeetCode】743. Network Delay Time 解题报告(Python)

    [LeetCode]743. Network Delay Time 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: ht ...

  8. 【LeetCode】886. Possible Bipartition 解题报告(Python)

    [LeetCode]886. Possible Bipartition 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu ...

  9. 【LeetCode】802. Find Eventual Safe States 解题报告(Python)

    [LeetCode]802. Find Eventual Safe States 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemi ...

  10. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

随机推荐

  1. TYVJ1864 守卫者的挑战

    P1864 [Poetize I]守卫者的挑战 时间: 1000ms / 空间: 131072KiB / Java类名: Main 描述 打开了黑魔法师Vani的大门,队员们在迷宫般的路上漫无目的地搜 ...

  2. ZOJ1586 QS Network

    QS Network Time Limit: 2 Seconds      Memory Limit: 65536 KB Sunny Cup 2003 - Preliminary Round Apri ...

  3. Server Data Synchronization Via Linux rsync、rsync+inotify Between Load Balance Server

    目录 . 远程文件同步的应用场景 . rsync+crontab . rsync+inotify 1. 远程文件同步的应用场景 在负载均衡集群的应用场景中,往往在多台web server的前端有一个提 ...

  4. Rootkit Hunter Sourcecode Learning

    目录 . Rootkit Hunter Introduce() . Source Code Frame() . do_system_check_initialisation() . do_system ...

  5. 修改eclipse/MyEclipse中包的显示结构为树形

    在右上边三角那里进去设置 选第一个是显示完整的包名,第二个显示的是树形结构,我们一般用第一种,如下图:

  6. 初学Struts2-自定义拦截器及其配置

    自定义拦截器,首先新建一个继承自AbstractInterceptor类的类,然后重写intercept方法,代码如下 public class HelloInterceptor extends Ab ...

  7. 改变字典内的value

    import re,os limit = "8000" username = "liuhuihuang" with open("users_dict& ...

  8. MySQL查询重复出现次数最多的记录

    MySQL查询的方法很多,下面为您介绍的MySQL查询语句用于实现查询重复出现次数最多的记录,对于学习MySQL查询有很好的帮助作用. 在有些应用里面,我们需要查询重复次数最多的一些记录,虽然这是一个 ...

  9. iOS-Auto property synthesis will not synthesize property 'delegate'; it will be implemented by its super

    今天在XCode6.3上面重写TabBar的时候,自定义tabBar的代理遇到的一个问题 在重写tabBar的代理的时候遇到了一个警告. 解决方法: 在.m文件中 警告消失.

  10. HttpResponse对象

    为了响应客户端的请求,同样定义了代表响应的类:HttpResponse类,它也定义在命名空间System.Web下,提供向客户端响应的方法和属性. HttpResponse常用属性和方法 响应对象用于 ...