写在前面的话:

  看了看自己的博客,从一月底开始就没怎么更新过,我也确实将近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. UVa 11988 Broken Keyboard (a.k.a. Beiju Text)

    题目复制太麻烦了,甩个链接 http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=18693 直接模拟光标操作时间复杂度较高,所以用链 ...

  2. java连接mysql(二)

    模拟转账成功时的业务场景 import java.sql.*; public class TransactionDemo1 { public static void main(String[] arg ...

  3. POJ2309BST(树状数组)

    BST Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 9182   Accepted: 5613 Description C ...

  4. IbatisNet的介绍和使用

    http://dragonsuc.cnblogs.com/archive/2006/07/04/ibatisnet.html IbatisNet的介绍和使用http://files.cnblogs.c ...

  5. js的基础学习

    alert() 函数在 JavaScript 中并不常用,但它对于代码测试非常方便. <!DOCTYPE html> <html> <body> <h1> ...

  6. SQL语句修改表字段名/修改字段长度/增加字段/删除字段

    修改字段名Exec sp_rename 'zxchem_Suggest.End_Date','Yj_Finish_Date','Column' 修改字段长度Alter Table zxchem_Sug ...

  7. 仿51job.com城市选择框特效

    650) this.width=650;" border="0" alt="" src="http://img1.51cto.com/att ...

  8. 使用C#进行图片转换格式,缩放,自动旋转,保留exif(转载)

    这几天心血来潮做了一个批量图片缩放,转换格式,并且可以根据exif的信息旋转图片,校正exif信息后保存的小程序.根据配置文件 指定需要的功能. 1 2 3 4 5 6 7 8 9 10 11 12 ...

  9. How can I style a JavaFX SplitMenuButton in CSS

    0 down vote favorite I try to style a SplitMenuButton in JavaFX. I've got a menuButton and a SplitMe ...

  10. Android Studio-设置switch/case代码块自动补齐

    相信很多和我一样的小伙伴刚从Eclipse转到Android Studio的时候,一定被快捷键给搞得头晕了,像Eclipse中代码补齐的快捷键是Alt+/ ,但是在AS中却要自己设置,这还不是问题的关 ...