Leetcode---Clone Graph

ArcGIS License Server点击启动没反应,许可管理器无法启动怎么办 4 当我们再打开ArcGIS License Server Administrator的时候。3 在【服务】中找到【ArcGIS License Manager】双击。无法启动ArcGIS License Server的情况。在使用ArcGIS的过程中,我们经常会遇到。专注GIS领域知识分享,交流行业软件技巧。欢迎关注,不定期分享GIS各种问题和技巧。1 右击我的电脑——【管理】服务状态——启动,确定即可。启动类型选择——自动。 阅读详情

这道题可以用DFS和BFS分别完成。

要说DFS和BFS讲的透彻的,还是算法导论,下面给出算法导论上的伪代码,注意,其中任何一行code都是非常值得玩味的:

BFS伪代码

BFS(G, s)
 1  for each vertex u ∈ V [G] - {s}
 2       do color[u] ← WHITE
 3          d[u] ← ∞
 4          π[u] ← NIL
 5  color[s] ← GRAY
 6  d[s] ← 0 
 7  π[s] ← NIL 
 8  Q ← Ø
 9  ENQUEUE(Q, s)
10  while Q ≠ Ø
11      do u ← DEQUEUE(Q) 
12         for each v ∈ Adj[u] 
13             do if color[v] = WHITE
14                   then color[v] ← GRAY
15                        d[v] ← d[u] + 1
16                        π[v] ← u 
17                        ENQUEUE(Q, v)
18         color[u] ← BLACK

当图中有环的时候,可能出现重复访问的情况,这时用color着色,防止重复访问已经访问过的节点。其实关键是Gray和White,Black就是标记这个节点是不是完全被访问完成了。

注意,之前访问过的节点根本不能进入队列。

DFS伪代码

DFS(G)
1  for each vertex u ∈ V [G]
2       do color[u] ← WHITE
3          π[u] ← NIL
4  time ← 0
5  for each vertex u ∈ V [G]
6       do if color[u] = WHITE
7             then DFS-VISIT(u)
DFS-VISIT(u)
1  color[u] ← GRAY
2  time ← time +1
3  d[u] <-time
4  for each v ∈ Adj[u]
5       do if color[v] = WHITE
6             then π[v] ← u
7                         DFS-VISIT(v)
8  color[u] <-BLACK
9  f [u] ▹ time ← time +1

注意,也用着色来避免重复访问,关键也是Gray和White。当一个节点之前被访问过的情况下,无法递归调用DFS-VISIT。

另外,我们平时在写DFS的时候,尽量脑子只思考两层,第一层for循环,第二层递归,否则很容易晕。


BFS代码:

unordered_map<UndirectedGraphNode*,UndirectedGraphNode *> mp;
unordered_map<UndirectedGraphNode*,bool> color;
UndirectedGraphNode * bfs(UndirectedGraphNode *node){
    if(node==NULL)
        return NULL;
    UndirectedGraphNode * root=new UndirectedGraphNode(node->label);
    mp[node]=root;
    queue<UndirectedGraphNode *> Q;
    Q.push(node);
    color[node]=true;
    while(!Q.empty()){
        UndirectedGraphNode * front=Q.front();
        Q.pop();
        for(int i=0;i<front->neighbors.size();i++){
            if(color[front->neighbors[i]]!=true){
                Q.push(front->neighbors[i]);
                color[front->neighbors[i]]=true;
                UndirectedGraphNode * temp=new UndirectedGraphNode(front->neighbors[i]->label);
                mp[front->neighbors[i]]=temp;
                mp[front]->neighbors.push_back(temp);
            }
            else{
                mp[front]->neighbors.push_back(mp[front->neighbors[i]]);
            }
        }
    }
    return root;
}

UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
    return bfs(node);
}

DFS代码:

unordered_map<UndirectedGraphNode*,UndirectedGraphNode *> mp;
unordered_map<UndirectedGraphNode*,bool> color;
UndirectedGraphNode * dfs(UndirectedGraphNode *node,UndirectedGraphNode *parent){
    if(node==NULL)
        return NULL;
    UndirectedGraphNode * me=NULL;
    color[node]=true;
    if(mp[node]==0){
        me=new UndirectedGraphNode(node->label);
        mp[node]=me;

    }
    else{
        me=mp[node];

    }
    if(parent!=NULL)
        parent->neighbors.push_back(me);
    for(int i=0;i<node->neighbors.size();i++){
        if(color[node->neighbors[i]]==true)
            me->neighbors.push_back(mp[node->neighbors[i]]);
        if(color[node->neighbors[i]]!=true)
            dfs(node->neighbors[i],me);
    }

    return me;
}

UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
    return dfs(node,NULL);
}




OpenCV实战:用C++和Python实现亚像素边缘检测(附完整代码) 本文详细介绍了使用OpenCV实现亚像素边缘检测的技术,通过C++和Python双语言代码解析,提升工业测量和医学影像中的检测精度。文章涵盖算法原理、核心实现步骤及工业应用案例,帮助开发者掌握亚像素精度处理技术,解决高精度场景中的边缘检测难题。 阅读详情

相关推荐

IMU660RA姿态解算实战:从传感器滤波到欧拉角输出的完整实现

本文详细介绍了IMU660RA姿态解算的完整实现过程,从传感器滤波到欧拉角输出。通过实战案例和代码示例,展示了如何有效处理陀螺仪和加速度计的噪声问题,并选择合适的算法进行数据融合和姿态解算。特别强调了欧拉角输出中的坐标系对齐和动态补偿技巧,帮助工程师快速掌握IMU660RA的应用。

weixin_42524762的博客 388

LeetCode Clone Graph

对一个无向图进行复制,图中的每一个节点都有自己的标签和自己相邻节点的列表。

DRFish 4612

PIVlab软件入门:从GUI操作到2D2C粒子测速实战

本文详细介绍了PIVlab软件在2D2C粒子测速中的入门与实战应用。从GUI操作到环境搭建,再到图像预处理和核心参数设置,帮助用户快速掌握这一基于MATLAB的开源工具。通过实际案例和技巧分享,展示了PIVlab在流体力学实验中的高效性和实用性。

weixin_42547431的博客 227

leetcode clone-graph(Java)

leetcode题目 clone-graph 题目描述 * Clone an undirected graph. Each node in the graph * contains a label and a list of its neighbors. 思路 * 1、递归实现 * 2、具体实现为:复制原节点,挂接邻居节点的复制节点到原节点的复制节点下 * 3、怎么复制邻居节点呢...

聚沙成塔 370

Krylov子空间与Arnoldi过程

一、应用背景 Krylov子空间方法是模型降阶(MOR)的一种,Krylov 子空间方法就是在Krylov子空间中寻找近似解。 二、Krylov子空间 n是原始矩阵的维度,m为降阶后矩阵的维度,通常m<<n。 三、Arnoldi 过程: 计算Km 的一组正交 对应上述MGS过程的python代码: import numpy as np def arnoldi_itera...

保持写作习惯,完成知识沉淀 6004

史上最小白之RNN详解

1.前言 网上目前已经有诸多优秀的RNN相关博客,但是我写博客的出发点主要是为了加深和巩固自己的理解,所以还是决定自己再进行一下总结和描述,如有不正确的地方欢迎指正~ 2.区分RNN 循环神经网络(Recurrent Neural Network),递归神经网络(Recursive Neural Network),你有没有发现他们的缩写都是RNN,那他们两个是同一回事儿吗?网上有一些博客把这两就当...

Tink1995的博客 4万+

leetcode Clone Graph

题目连接 https://leetcode.com/problems/clone-graph/ Clone Graph Description Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ’s undirected grap...

dong12276的博客 153

通信算法之283:大疆DJI云哨系统-DJI DroneID物理层协议-解速率匹配及Turbo译码

3. 完整云哨接收机,接收灵敏度。交流: 1279682290 ,2. Turbo译码模块。1. 解速率匹配模块。

leegang12的专栏 868

【LeetCode】133. Clone Graph 解题报告(Python & C++)

作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录题目描述题目大意解题方法DFSBFS日期 题目地址:https://leetcode.com/problems/clone-graph/ 题目描述 Given a reference of a node in a connected undirected graph, return...

负雪明烛 4513

特殊通信领域场景应用:基于Simulink的数字预失真(DPD)算法仿真建模示例

增益压缩:高功率输入时输出信号的增益下降。相位失真:输入信号的相位随功率变化而改变。带外干扰:非线性失真会引入额外的频谱分量,影响邻道信号。多项式模型:用多项式拟合功率放大器的非线性特性。查找表(LUT):通过离线训练生成预失真映射表。自适应算法:实时调整预失真参数以动态补偿失真。发送端:生成随机比特流并调制为射频信号。预失真模块:对输入信号进行预失真处理。功率放大器模块:模拟非线性失真。接收端:解调信号并评估误码率(BER)。

xiaoheshang_123的博客 274

OpenClaw人人养虾:接入即时通讯平台Zalo

通过 Zalo Official Account(OA,官方账号)API,可以将 OpenClaw 接入 Zalo,实现面向越南用户的自动化客服和互动。

王国平的博客 437

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

第14.5章 高翔博士最新开源框架Lightning-LM源码解读(五):揭秘位姿图优化核心模块,从数学原理到代码实现

本文介绍了Lightning-LM框架中的位姿图优化(PGO)模块实现。该模块通过融合多源定位信息(激光定位、激光里程计、DR等),构建并优化位姿图来获得更精确的位姿估计。 主要内容包括: 模块概况与数据流程:初始化配置→添加PGO帧→分配位姿→优化求解→更新位姿→滑动窗口 16个核心函数详解:从构造函数到边缘化处理,涵盖完整的PGO工作流程 关键技术点:噪声参数设置、优化问题构建、约束添加、异常值处理等 关键数据结构:帧队列管理、顶点和边构建、优化统计信息收集 该PGO模块采用增量式优化方式,支持多种约束

行知SLAM 1216

LeetCode: Clone Graph

LeetCode: Clone Graph LeetCode: Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's undirected graph seria...

weixin_33953384的博客 101

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Leetcode 133 Clone Graph(STL)

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

不慌不忙、不急不躁 412

深度学习工具包 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 题解

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

cannonjinx的博客 1223

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

【Leetcode】 Clone Graph

题目链接: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:

业精于勤,荒于嬉 2651

LeetCode题解: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, an

追风筝的吃货,汪~ 515

leetcode clone graph

题目描述 https://oj.leetcode.com/problems/clone-graph/ 思路 第一遍遍历图,在每个节点的neighbors列表的末尾加上一个selfCopyNode,即对该节点的复制节点。 第二遍遍历图,对每个节点的复制节点,让它的每个neighbor都是原节点对应neighbor复制节点。 第三遍遍历图,移除每个节点的selfCopyNode,还原原来

飘羽逸狂 404

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

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

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

mbinary 176

【LeetCode】Clone_Graph

这也是LeetCode上的一道题目,描述如下:

ice4026的专栏 516

leetcode:Clone Graph

复制图的结构, /** * Definition for undirected graph. * class UndirectedGraphNode { * int label; * List neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList();

635

leetcode之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 separ

momentforver的专栏 623

LeetCode //C - 133. Clone Graph

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

Made in Code 240

LeetCode Clone Graph

大家好,我是刘天昊,那么这次的题目厉害了 因为之前我的blog也没有关于图结构的操作,这次特地找了leetcode总不多的图结构的操作题 先看题目 Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's undirected

玉界尺的博客 359
上一篇: Leetcode---Sum Root to Leaf Numbers
下一篇: Leetcode---Subsets
我把葡萄酿成酒
博客等级 码龄12年 275粉丝 198原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值