LeetCode 323. Number of Connected Components in an Undirected Graph

leetcode323. 无向图中连通分量的数目 给定编号从 0 到 n-1 的 n 个节点和一个无向边列表(每条边都是一对节点),请编写一个函数来计算无向图中连通分量的数目。 示例 1: 输入: n = 5 和 edges = [[0, 1], [1, 2], [3, 4]]      0          3      |          |      1 — 2    4  输出: 2 示例 2: 输入: n = 5 和 edges = [[0, 1], [1, 2], [2, 3], [3, 4]]      0           4      |           |      1 — 2 — 3 输出:  1 注意: 你可以 立即下载
#include <vector>
#include <unordered_map>
#include <queue>
#include <iostream>
using namespace std;
/*
  Given n nodes labeled from 0 to n-1 and a list of undirected edges, write a function
  to find the number of connected components in an undirected graph.
  For example:
  0
  |
  1 ---> 2    4--->3
  Given n = 5 and edges = [[0,1], [1, 2], [3, 4]] return 2.
*/
// it is pretty straightforward to come up BFS algorithm.
// But the first task is to change the pair vector into graph node-edges form.
// we can use hashMap to do that. unordered_map<int, vector<int> > hashMap.
void BFS(unordered_map<int, vector<int> >& hashMap, int node, unordered_map<int, bool>& visited) {
  queue<int> nodes;
  nodes.push(node);
  while(!nodes.empty()) {
    int tmp = nodes.front();
    nodes.pop();
    if(visited[tmp]) continue;  // if visited, skip it.
    visited[tmp] = true;
    auto iter = hashMap.find(tmp);
    vector<int> edges = iter->second;
    for(int k = 0; k < edges.size(); k++) {
      nodes.push(edges[k]);
    }
  }
}
int findNumOfConnectedComponent(int n, vector< vector<int> >& edges) {
  unordered_map<int, vector<int> > hashMap;
  unordered_map<int, bool> visited;
  int count = 0;
  for(int i = 0;  i < edges.size(); ++i) {
    hashMap[edges[i][0]].push_back(edges[i][1]);
    hashMap[edges[i][1]].push_back(edges[i][0]);
  }
  auto iter = hashMap.begin();
  while(iter != hashMap.end()) {
    visited[iter->first] = false;
    iter++;
  }
  auto it = visited.begin();
  while(it != visited.end()) {
    if(!(it->second)) {
      BFS(hashMap, it->first, visited);
      count++;
    }
    it++;
  }
  return count;
}
int main(void) {
  vector< vector<int> > edges {
  {0, 1},
  {1, 2},
  {3, 4},
  {5, 6},
  {7, 7}};
  cout << findNumOfConnectedComponent(8, edges) << endl;
}
 

从零开始使用CubeMX配置STM32使用lwip实现httpd服务器以及使用vscode编辑阅读keil代码(三) 使用stm32搭载lwip实现HTTPd服务器 阅读详情

相关推荐

SRAM故障排查实战:如何用Nano Prober定位6T存储单元的异常点

本文详细介绍了在SRAM故障排查中,如何运用Nano Prober(纳米探针)技术精准定位6T存储单元的内部异常。面对传统方法难以发现的电性参数漂移(如晶体管阈值电压偏移)或微小物理缺陷,Nano Prober能直接对单个6T单元内的晶体管进行I-V特性测量,结合失效模式分析,有效解决读写错误等疑难问题,是芯片失效分析的关键工具。

v5w6x的博客 664

力扣(LeetCode)323. 无向图中连通分量的数目(2022.11.20)

链接:https://leetcode.cn/problems/number-of-connected-components-in-an-undirected-graph。给定一个整数 n 和一个数组 edges ,其中 edges[i] = [ai, bi] 表示图中 ai 和 bi 之间有一条边。输入: n = 5, edges = [[0,1], [1,2], [2,3], [3,4]]输入: n = 5, edges = [[0, 1], [1, 2], [3, 4]]

ChaoYue_miku的博客 1305

微信h5 支付,已经获得weixin://wap/pay?prepayid,但是无法调起微信客户端支付

结果几个接口,最终获得到到一直包含调起微信客户端的支付链接 但是直接打开这个页面,却不能调起微信客户端支付,原因是,在打开新页面的时候,需要设置a.rel = "noreferrer"; <body> <a href="javascript:void(0)" onclick="openNewWindowNoreferrer(this)">点击支付</a&...

qq_31683775的博客 4万+

leetcode:323. 无向图中连通分量的数目

你可以假设在 edges 中不会出现重复的边。而且由于所以的边都是无向边,[0, 1] 与 [1, 0] 相同,所以它们不会同时在 edges 中出现。

OceanStar的博客 937

数字IC后端设计实现 | PR工具中到底应该如何控制density和congestion?(ICC2&Innovus)

数字IC后端设计实现中到底应该如何控制cell density和congestion?(ICC2和Innovus两种解决方案)

weixin_37584728的博客 7112

【S32K3 MCAL配置】-3.4-CANFD配置-接收特定的“经典CAN/CANFD标准帧”和“经典CAN/CANFD扩展帧”(基于MCAL+FreeRTOS)

【S32K3 MCAL配置】-3.4-CANFD配置-接收特定的“经典CAN/CANFD标准帧”和“经典CAN/CANFD扩展帧”(基于MCAL+FreeRTOS)

「汽车电子助手」的博客 696

Leetcode—323.无向图中连通分量的数目【中等】Plus

测试结果 之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

Atticus的博客 973

【1.2】Costas环的基本原理概述

Costas环是一种用于载波恢复的相干解调技术,可直接从BPSK等抑制载波信号中恢复本地载波并完成解调。其核心结构包含同相/正交双支路处理,通过混频、低通滤波后,利用I/Q支路信号乘积进行相位误差检测,经环路滤波器调节VCO输出频率,实现载波同步。课程将重点讲解Costas环的MATLAB仿真实现、系统性能分析及FPGA开发,包括信号产生、频偏模拟、滤波器设计等模块,并通过AWGN信道和不同频偏条件下的测试验证系统性能。该技术无需单独提取载波,在数字通信系统中具有重要应用价值。

fpga/matlab/simulink算法仿真工程 450

Leetcode 323.无向连通图中的连通分量个数

Time: 20190903 Type: Medium 题目描述 给定编号从 0 到 n-1 的 n 个节点和一个无向边列表(每条边都是一对节点),请编写一个函数来计算无向图中连通分量的数目。 示例 1: 输入: n = 5 和 edges = [[0, 1], [1, 2], [3, 4]] 0 3 | | 1 --- 2 4 输出: 2 示例...

Bing's Blog 6265

TIA博途中S7-1200进行MODBUS TCP通信(作为服务器)的具体方法演示

TIA博途中S7-1200进行MODBUS TCP通信(作为服务器)的具体方法演示

Robot_PLC_HMI_Automation 8607

Allegro如何设置走线自动删除重复走线操作指导

Allegro如何设置走线是自动删除重复走线操作指导在PCB布线的时候,点到点需要重复走一段线的时候,希望原来的线段自动被删除,Allegro设计的时候支持这个操作如下图,重复走中间的线段的时候,希望下方的走线自动删除具体操作如下This section is describe what the function allegro have ,helpfully could let user know more about allegroAllegro Design and Analysis includes

weixin_54787054的博客 4497

leetcode:323. 无向连通图中的连通分量个数

建立一个root数组,下标和节点值相同,此时root[i]表示节点i属于group i,我们初始化了n个部分 (res = n),假设开始的时候每个节点都属于一个单独的区间,然后我们开始遍历所有的edge,对于一条边的两个点,他们起始时在root中的值不相同,这时候我们我们将结果减1,表示少了一个区间,然后更新其中一个节点的root值,使两个节点的root值相同,那么这样我们就能把连通区间的所有节点的root值都标记成相同的值,不同连通区间的root值不相同,这样也能找出连通区间的个数。

OceanStar的博客 1302

Unity零基础到入门☀️| 万字教程 讲解Unity中的数据存储 PlayerPrefs、XML、JSON【建议收藏】

本文章是Unity零基础到入门专栏的系列文章。 适合对Unity3D引擎感兴趣的小伙伴学习,偏向于新手学习! 本篇文章就来介绍一下Unity中三种基本的数据存储方式:PlayerPrefs、XML、JSON

努力前行,总会成为自己心中的那道光 8万+

Leetcode 323. Number of Connected Components in an Undirected Graph(python+cpp)

Leetcode 323. Number of Connected Components in an Undirected Graph题目解法1:DFS解法2:unionfind 题目 Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write ...

qq_37821701的博客 1825

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

假人有限元模型

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

[leetcode323]Number of Connected Components in an Undirected Graph

Question: Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph

清空 1110

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

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

【LeetCode】323. Number of Connected Components in an Undirected Graph 解题报告 (C++)

作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录题目描述题目大意解题方法并查集日期 题目地址:https://leetcode-cn.com/problems/number-of-connected-components-in-an-undirected-graph/ 题目描述 Given n nodes la...

负雪明烛 1617

深度学习工具包 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】323. Number of Connected Components in an Undirected Graph

题目地址: https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/ 求无向图的连通分量,可以假定没有平行边。可以用DFS求解,设一个visited数组,每遇到一个未访问过的节点就对其进行DFS,同时将搜索到的节点都标记为访问过;访问的同时统计连通分量的个数。思想上类似于floodfil...

数学、算法爱好者的博客 550

LeetCode323 Number of Connected Components in an Undirected Graph

Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]] 0 3 | | 1 --- 2 4 Output: 2 it is quite easy to understtandi this problem. now, how to solve it? if you really think about t...

Tech in Pieces 323

Leetcode 323: Number of Connected Components in an Undirected Graph

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Example 1: Inpu...

weixin_46442857的博客 267

[leetcode] 323. Number of Connected Components in an Undirected Graph 解题报告

题目链接:https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/ Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), wr

小榕流光的专栏 1713

LeetCode 323. Number of Connected Components in an Undirected Graph (Medium)

Description: Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Ex...

weixin_45744426的博客 241

Leetcode 刷题 - 323 - Number of Connected Components in an Undirected Graph

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Example 1:

883

LeetCode 323. Number of Connected Components in an Undirected Graph(连通分量)

原题网址:https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/ Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), wr

James Pan 2315

leetcode| 323. Number of Connected Components in an Undirected Graph(并查集/DFS/BFS)

题目 题目描述:一张含n节点的无向图,以及一组无向边,编写一个函数来查找无向图中连接的组件的数量。 Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]] 0 3 | | 1 --- 2 4 Output: 2 分析 解法DFS/BFS/并查集,DFS和BFS时间复杂度均为O...

mike_learns_to_rock的博客 768
上一篇: LeetCode 157: Read N Characters Given Read4
下一篇: LeetCode 32. Longest Valid Parentheses
ActiveCoder
博客等级 码龄11年 4粉丝 345原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值