LeetCode133. Clone Graph

从SolidWorks到URDF:插件使用、关节配置与PyBullet仿真避坑指南 本文提供了一份从SolidWorks导出URDF模型并导入PyBullet进行仿真的完整实战指南。详细讲解了SolidWorks插件的正确安装与配置、关节类型的选择与坐标系对齐的核心技巧,并针对PyBullet仿真中常见的模型散架、路径错误、物理属性异常等问题提供了深度避坑解决方案,帮助机器人开发者高效完成从设计到仿真的全流程。 阅读详情

题目:

https://leetcode.com/problems/clone-graph/

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 #.

First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
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
         / \
         \_/

思路:

题意:克隆一个图。

BFS遍历图,一边遍历,一边完成克隆。用map记录原来图的节点和克隆图的节点情况,防止克隆过的节点再被new一次。每copy一个原节点,就把原节点与克隆节点放入map中,原节点与克隆节点对应。如果后面的遍历遇到在map中的原节点,表明这个原节点已经被copy过了,不用新new一个节点来再次copy。

代码:

/**
 * 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;
        }
        UndirectedGraphNode* cur=NULL;
        UndirectedGraphNode* start=NULL;
        UndirectedGraphNode* connect=NULL;
        queue<UndirectedGraphNode*> q;
        q.push(node);
        unordered_map<UndirectedGraphNode*,UndirectedGraphNode*> m;
        start=new UndirectedGraphNode (node->label);
        m[node]=start;
        while(!q.empty()){
            cur=q.front();
            q.pop();
            int len=cur->neighbors.size();
            for(int i=0;i<len;i++){
                connect=cur->neighbors[i];
                if(m.find(connect)==m.end()){
                    UndirectedGraphNode* nodeCopy=new UndirectedGraphNode(connect->label);
                    m[connect]=nodeCopy;
                    q.push(connect);
                }
                m[cur]->neighbors.push_back(m[connect]);//与原节点对应的克隆节点添加相邻节点
            }
        }
        return start;
    }
};
【绝对要收藏-优秀论文范文】高项-度量绩效域 摘要:本文基于某水库数字孪生平台建设项目(2022.9-2023.5,645.97万元)的管理实践,从信息系统度量绩效域角度展开论述。项目构建了包含防洪调度等6大子系统的数字平台,实现洪水"四预"功能。重点分析了度量绩效域的五大要点:制定有效指标(如成本±8%偏差阈值)、多维数据采集、预警临界值设定、基于趋势的主动干预和持续改进机制。特别阐述了绩效问题的诊断方法,包括设备采购全周期成本分析、阶段性成本报告制度等。项目状态展示采用三维可视化看板,集成进度、成本、质量等多维度实时数据,最终实 阅读详情

相关推荐

IEEE Transactions模板中参考文献作者缩写、期刊名缩写

本文章记录如何在IEEE Transactions的模板中,解决参考文献的作者缩写、期刊名字缩写的问题。

weixin_43981621的博客 1万+

LeetCode 133. Clone Graph 题解

本题是图的基本操作,考察深拷贝的实现。使用哈希表记录映射关系DFS 或 BFS 遍历图避免重复创建节点。

cannonjinx的博客 1239

【计算机组成原理】实验4:单周期CPU(Verilog)中海大

【计算机组成原理】实验4:单周期CPU

m0_63023532的博客 3666

Leetcode 133 Clone Graph(STL)

题目连接:Leetcode 133 Clone Graph解题思路:对每个结点用new方法新建一个一样的结点,并且将对应的label和新节点指针的对应关系保存在Map中,每次遍历一个结点是,对应在节点的neighbors中放入对应新结点的指针。/** * Definition for undirected graph. * struct UndirectedGraphNode { * ...

不慌不忙、不急不躁 414

sklearn2pmml xgboost缺失值(missing)处理的坑

sklearn2pmml xgboost缺失值(missing)如何处理 今天同事在部署xgboost pmml模型时遇到了大坑,线上spark预测和本地python预测结果怎么都不对应,记录一下处理过程。 看了下同事的代码,貌似也没有问题 from sklearn2pmml import PMMLPipeline from sklearn2pmml import sklearn2pmml fro...

Skycrab 8979

从拧螺丝到精密装配:三菱伺服电机扭矩控制在工业自动化中的实战解析

本文深入解析三菱伺服电机扭矩控制在工业自动化中的实战应用,重点介绍MR-J4系列伺服系统的高精度扭矩响应技术。从螺丝紧固到精密装配,详细讲解扭矩控制模式的选择、硬件配置、参数设置及典型故障排查方案,帮助工程师提升生产效率和产品质量。

weixin_29186249的博客 477

LeetCode 133. Clone Graph(dfs)

题目来源:https://leetcode.com/problems/clone-graph/ 问题描述 133.Clone Graph Medium Givena reference of a node in aconnectedundirected graph, return adeep copy(clone) of the graph. Each node in the ...

da_kao_la的博客 226

Selenium自动化测试遇到shadow-root元素?3种实用解决方案帮你搞定

本文针对Selenium自动化测试中遇到shadow-root元素难以定位的常见问题,提供了三种实用的解决方案。详细阐述了通过JavaScript直接穿透Shadow DOM、利用浏览器工具快速获取JS Path以及使用Python第三方库进行优雅封装的方法,并分享了提升脚本健壮性的实战策略与最佳实践,帮助测试人员有效应对现代Web组件化开发带来的挑战。

code8的博客 419

leetcode 133. Clone Graph的思路与python实现

Givena reference of a node in aconnectedundirected graph, return adeep copy(clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors. Example:...

qq_35175413的博客 322

数据分片的三种方式:哈希、一致性哈希、按照数据范围分片

数据分片就是按照一定的规则,将数据集划分成相互独立、正交的数据子集,然后将数据子集分布到不同的节点上。通过设计合理的数据分片规则,可将系统中的数据分布在不同的物理数据库中,达到提升应用系统数据处理速度的目的。三种常用的数据分片方式:1. 哈希分片2. 一致性哈希分片(Consistent Hash)3. 按照数据范围分片(Range Based)数据分片的应用场景:1. 数据库扩展2. 分布式缓存对集群部署多个缓存节点,提高缓存的处理能力。

wjianwei666的专栏 1160

PCL:读写pcd点云的两种方式

本文介绍了PCL读写点云的两种方式:PCDReader,PCDWriter;loadPCDFile,savePCDFile.

孙悟空 1万+

[一起来刷leetcode吧][4]--No.133 Clone Graph

这篇文章是程序自动发表的,详情可以见这里 这是leetcode的第133题--Clone Graph &emsp;&emsp;题目 Clone an undirected graph. Each node in the ...

mbinary 176

SAP CRP能力计划详细说明操作及相关配置

2、求助朋友同事的希望破灭后,网上找了资料发现在百度搜索的资料基本都是没有说明白什么才产能计划,都没有详细的操作说明,然后用google去搜索了一些相关的文章,好像也没有详细的文章。然后也去SAP的官网搜索了相关的文章,都是文字性的表述,对系统的配置都没有很大的帮助,很久之前有记得在隐身人的博客中有提到CRP的能力计划的文章,然后试着去找了一下相关的文章。5、首先产能排产肯定涉及的就是是能力的问题,能力第一个能想到的就是工作中心中的能力页签,在流程制造中也叫资源,其实都是一个东西。

我小时候很黑的博客 4545

LeetCode133—Clone Graph

LeetCode133—Clone Graph

上善若水 874

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

LeetCode //C - 133. Clone Graph

【代码】LeetCode //C - 133. Clone Graph。

Made in Code 243

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

[leetcode] 133 Clone Graph

问题描述: 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 separat

追梦船的专栏 1157

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LeetCode 133: Clone Graph

LeetCode 133: Clone Graph思路 需要考虑自环和两个节点有多条边的特殊情况,这种情况下,不能生成新的节点,而是引用已有节点; 利用Hashtable记录已经存放的节点; 代码import java.util.Hashtable; public class Solution { public UndirectedGraphNode cloneGraph(Undirecte

u010759408的博客 306

Leetcode 133. Clone Graph

Leetcode 133. Clone Graph Given a reference of a node in a connected undirected graph. Return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors. class Node { public int val; pub

chelseajcole的专栏 413

133. Clone Graph Leetcode Python

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

hyperbolechi的专栏 1874

leetcode - 133. Clone Graph

算法系列博客之DFS DFS(深度优先搜索)在图论的范畴里可以通俗的解释为 总是优先向相连接未访问的下一节点搜索,直到没有这样的节点即返回上一节点 DFS标准格式:Input: G = (V, E) is a Graphprocedure dfs(G): for all v∈V: visited(v) = false for all v∈V:

Quiteen的博客 395

Leetcode 133 Clone Graph

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

无名山丘,崛起成峰 924

LeetCode133——Clone Graph

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

代码菌的blog 1355

leetcode 133 —— Clone Graph

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 ea

ziquanbang的专栏 390

[leetcode] 133. Clone Graph @ python

原题 https://leetcode.com/problems/clone-graph/ 解法 DFS, 定义dfs函数, 返回node的副本, base case是当node在字典中时, 直接返回dic[node]. 代码 """ # Definition for a Node. class Node(object): def __init__(self, val, neighbors...

闲庭信步 388

LeetCode 133 Clone Graph

Deep copy of a connected undirected graph, and there are some similar problems like this like: clone a N-ary tree. /* // Definition for a Node. class Node { public int val; public List<Node> neighbors; public Node() {} public Node(i

Tech in Pieces 315

【leetcode】133. Clone Graph

题目: 思路: 图的深度优先遍历。我用一个node_map把新克隆的node保存下来,使得原始node的val值映射到新克隆node的指针。因为val值就是index,是唯一的,所以我们只需要根据原始node的val值,从node_map中找到对应的新克隆的node指针即可。每次递归时,遍历当前node的所有邻接点,如果邻接点被访问过,则node_map中一定保存着其对应的克隆node;如果邻...

zxc120389574的博客 218
上一篇: LeetCode160. Intersection of Two Linked Lists
下一篇: C/C++知识点整理(2)
_IanXiao
博客等级 码龄12年 84粉丝 241原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址