写在前面的话:

  看了看自己的博客,从一月底开始就没怎么更新过,我也确实将近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. 人工鱼群算法-python实现

    AFSIndividual.py import numpy as np import ObjFunction import copy class AFSIndividual: "" ...

  2. BZOJ-2037 Sue的小球 DP+费用提前

    似乎很早时学长考过很类似的? 2037: [Sdoi2008]Sue的小球 Time Limit: 10 Sec Memory Limit: 64 MB Submit: 558 Solved: 300 ...

  3. 【poj1067】 取石子游戏

    http://poj.org/problem?id=1067 (题目链接) 题意 有两堆石子,数量任意,可以不同.游戏开始由两个人轮流取石子.游戏规定,每次有两种不同的取法,一是可以在任意的一堆中取走 ...

  4. POJ1125 Stockbroker Grapevine

    Description Stockbrokers are known to overreact to rumours. You have been contracted to develop a me ...

  5. .net Int16 、(int Int32)、 Int64 的区别

    关于什么是16位整数,32位整数,64位整数,请看这里:http://www.cnblogs.com/EasonJim/p/4837061.html Int16 值类型表示值介于 -32768 到 + ...

  6. OKR详解及其实施

    这阵子大家一直在讨论Google的绩效考核方法OKR,我们发现很多文章和说法存在错误和误导,现将其来龙去脉,操作步骤,操作技巧阐述如下,供大家参考. OKR全称是Objectives and Key ...

  7. PHP中soap的使用例子

    PHP 使用soap有两种方式. 一.用wsdl文件 服务器端. <?phpclass service{ public function HelloWorld() { return " ...

  8. IOS基础之 (十) 内存管理

    一 基本原理 1.什么是内存管理 移动设备的内存有限,每个app所能占用的内存是有限制的. 当app所占用的内存较多时,系统会发出内存警告,这时得回收一些不需要再使用的内存空间.比如回收一些不需要使用 ...

  9. MyEclipse使用SVN进行项目版本控制

    一.搭建SVN服务器. 例如,使用VisualSVN Server,下载后安装. (1)在Repositories(版本库)上右击,新建Repository,选择Regular FSFS reposi ...

  10. asp.net缓存(转)

    转自:http://www.cnblogs.com/knowledgesea/archive/2012/06/20/2536603.html 一.缓存概念,缓存的好处.类型.            缓 ...