博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode: Clone Graph
阅读量:5254 次
发布时间:2019-06-14

本文共 2638 字,大约阅读时间需要 8 分钟。

这题的思路就是建一个old graph到新的graph点的对应map,queue表示还未访问过的old graph的点的队列,如果queue的front的点的neighbors vector里有未访问的点就添加到队列里。

1 /** 2  * Definition for undirected graph. 3  * struct UndirectedGraphNode { 4  *     int label; 5  *     vector
neighbors; 6 * UndirectedGraphNode(int x) : label(x) {}; 7 * }; 8 */ 9 class Solution {10 public:11 UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {12 // IMPORTANT: Please reset any member data you declared, as13 // the same Solution instance will be reused for each test case.14 if (node == NULL) return NULL;15 map
S;16 UndirectedGraphNode *res = new UndirectedGraphNode(node->label);17 S[node] = res;18 queue
que;19 que.push(node);20 while (!que.empty()) {21 UndirectedGraphNode *t = que.front();22 que.pop();23 for (int i = 0; i < t->neighbors.size(); i++) {24 UndirectedGraphNode *nei = t->neighbors[i];25 if (S.count(nei)) S[t]->neighbors.push_back(S[nei]);26 else {27 que.push(nei);28 UndirectedGraphNode *tmp = new UndirectedGraphNode(nei->label);29 S[nei] = tmp;30 S[t]->neighbors.push_back(tmp);31 }32 }33 }34 return res;35 }36 };

 C#

1 /** 2  * Definition for undirected graph. 3  * public class UndirectedGraphNode { 4  *     public int label; 5  *     public IList
neighbors; 6 * public UndirectedGraphNode(int x) { label = x; neighbors = new List
(); } 7 * }; 8 */ 9 public class Solution {10 public UndirectedGraphNode CloneGraph(UndirectedGraphNode node) {11 if (node == null) return null;12 Dictionary
S = new Dictionary
();13 UndirectedGraphNode ans = new UndirectedGraphNode(node.label);14 S.Add(node, ans);15 Queue
que = new Queue
();16 que.Enqueue(node);17 while (que.Count != 0) {18 UndirectedGraphNode peek = que.Peek();19 que.Dequeue();20 for (int i = 0; i < peek.neighbors.Count; i++) {21 UndirectedGraphNode nei = peek.neighbors[i];22 if (S.ContainsKey(nei)) S[peek].neighbors.Add(S[nei]);23 else {24 que.Enqueue(nei);25 UndirectedGraphNode tmp = new UndirectedGraphNode(nei.label);26 S.Add(nei, tmp);27 S[peek].neighbors.Add(tmp);28 }29 }30 }31 return ans;32 }33 }
View Code

 

转载于:https://www.cnblogs.com/yingzhongwen/p/3404617.html

你可能感兴趣的文章
中文系统 上传file的input显示英文
查看>>
android permission
查看>>
【译】在Asp.Net中操作PDF - iTextSharp - 使用字体
查看>>
.net 文本框只允许输入XX,(正则表达式)
查看>>
实验2-2
查看>>
android smack MultiUserChat.getHostedRooms( NullPointerException)
查看>>
[置顶] Linux终端中使用上一命令减少键盘输入
查看>>
BootScrap
查看>>
Java实现二分查找
查看>>
php7 新特性整理
查看>>
RabbitMQ、Redis、Memcache、SQLAlchemy
查看>>
03 线程池
查看>>
手机验证码执行流程
查看>>
设计模式课程 设计模式精讲 2-2 UML类图讲解
查看>>
Silverlight 的菜单控件。(不是 Toolkit的)
查看>>
jquery的contains方法
查看>>
linux后台运行和关闭SSH运行,查看后台任务
查看>>
桥接模式-Bridge(Java实现)
查看>>
303. Range Sum Query - Immutable
查看>>
C# Dynamic通用反序列化Json类型并遍历属性比较
查看>>