LeetCode 547: Friend Circles (并查集好题)

LeetCode第547题 朋友圈 Friend Circles -- 超详细解析 1、题目描述 https://leetcode-cn.com/problems/friend-circles/ 2、解析 3、代码 class Solution { final int N = 210; int[] p = new int[N]; int find(int x){ if(p[x] != x){ p[x] = find(p[x]); } return p[... 阅读详情
  1. Friend Circles
    Medium

There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.

Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.

Example 1:

Input:
[[1,1,0],
[1,1,0],
[0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
The 2nd student himself is in a friend circle. So return 2.

Example 2:

Input:
[[1,1,0],
[1,1,1],
[0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.

Constraints:

1 <= N <= 200
M[i][i] == 1
M[i][j] == M[j][i]

解法1:并查集
我一开始把这题当成找岛屿个数那题了。但这题不一样,因为主对角线上面的点表示每个人,其他的点表示人与人之间的关系,两种点不一样,不能混作一团。
我的解法是用并查集,先把ans=n。然后沿着主对角线开始,每行往右找,如果是1,就和主对角线的那个人join,join过程中asn–。最后返回ans。

class Solution {
public:
    int findCircleNum(vector<vector<int>>& M) {
        int n = M.size();
        if (n == 0) return 0;
        ans = n;
        father.resize(n);

        for (int i = 0; i < n; ++i) {
                father[i] = i;
        }

        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (M[i][j] == 1) {
                    join(i, j);
                }
            }
        }
        
        return ans;
        
   }
private:
    vector<int> father;
    int ans = 0;
    int find(int x) {
        if (father[x] == x) {
            return x;
        }
        return father[x] = find(father[x]);
    }
    
    void join(int x, int y) {
        int fatherX = find(x);
        int fatherY = find(y);
        if (fatherX != fatherY) {
            father[fatherX] = fatherY;
            ans--;
        }
    }
    
};
LeetCode算法题集-547. Friend Circles(朋友圈) 有个班级,里面有N个学生,他们之中有些是朋友有些不是,比如如果A是B的朋友,B是C的朋友,那么A就是C的间接朋友,我们定义所谓的朋友圈就是由直系和间接朋友所组成的群体。 给定一个N*N的矩阵M,代表这个班级里所有学生的朋友关系,如果M[i][j] = 1,那么第i个和第j个学生就是互为直系朋友,不为1的话就不是朋友。而你的任务就是输出整个班级里总的朋友圈数量。 英语原文: There 阅读详情

相关推荐

WhatsApp网页版扫码分析

扫码登录本质上是WhatsApp的多设备登录,设备之间可以独立运行,那么当我们首次通过WhatsApp扫码登录二维码时,到底发生了那些事情?交换了那些数据?

SocialMarketing的博客 5230

靠谱程序员

靠谱程序员

huangyongf的博客 2561

TEM图像处理实战指南:从基础操作到金属材料分析

本文提供了一份全面的透射电镜(TEM)图像处理实战指南,涵盖从基础操作到金属材料深度分析的全流程。重点讲解了TEM图像预处理、选区电子衍射(SAED)标定、高分辨像(HRTEM)分析及STEM图像应用等核心技能,并结合金属材料(如铝合金、钢)的析出相鉴定、位错分析和界面结构研究等实际案例,帮助研究者从原始数据中准确提取晶体结构、缺陷及成分信息。

weixin_29284201的博客 208

Friends

Courteney Cox Arquette (Monica Gellar) 莫尼卡:考特妮·考克斯·阿奎德 个人资料 原名:考特妮·巴斯·考克斯 生日:1964年6月17日 出生地:亚拉巴马州 伯明翰 身高:五英尺五英寸 教育:布鲁克高中 华盛顿贝隆山学院(建筑专业,一年级退学) 影迷通讯地址: C/O Creative Anists Agency 9830 Wilshire Blvd. B

Tjerry的专栏 2583

ISP一键下载电路分析+74HC1G66GW(信号图)

之前要不用的最小系统的开发板要不就是用的SWD调试口,没有注意过ISP一键下载电路是个怎么回事,因为需要就简单的看了一下野火的ISP一键下载电路。 默认情况一下,一般我们的程序都是从用户闪存也就是内部的FLASH启动的, 对于F103RCT6来说ROM的大小是512kb,启动地址位0x8000000,这个在IDE keil里可以看的到,如下图。 首先简单理解一下ISP是什么: 可以把他理解为芯片厂商出场时固化在ROM当中的一段程序,它的功能就是把你写的程序一点点的搬运到FLASH当中,它引出了两个引脚

lipengyu1363658871的博客 4861

Frida实战:如何用adb快速连接网易mumu模拟器进行参数Hook(附常见CPU架构问题排查)

本文详细介绍了如何使用Frida和adb快速连接网易MuMu模拟器进行参数Hook,包括环境配置、架构适配、Frida-server部署及常见问题排查。特别针对CPU架构兼容性问题提供了实用解决方案,帮助开发者高效完成逆向调试任务。

weixin_29274969的博客 289

msysgit使用说明

http://jingyan.baidu.com/article/e52e36154233ef40c70c5153.html

小飞侠的博客 222

Docker+vLLM内网离线部署Qwen3 流程

本文介绍了在CentOS 7系统下进行VLLM容器化部署Qwen3-32B大模型的内网离线方案。首先需准备Nvidia显卡驱动、CUDA 12.4和Docker环境。通过联网机器拉取vllm/vllm-openai镜像并导入内网服务器,同时从魔塔社区下载模型文件。部署时使用docker run命令启动容器,配置了GPU资源、内存共享、端口映射等参数,特别指定了模型路径、并行计算、内存利用率等关键参数。该方案实现了大模型在内网环境的安全高效部署,适用于需要离线运行的AI推理场景。

qq_42881308的博客 1036

采用Cipher DES针对文件加密、解密

由于经常用一些加密或者解密文件的,所以写了一个简单的采用Cipher DES针对文件加密、解密的工具类,记录一下,防止以后忘记了! ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ...

小飞侠的博客 541

[RK3568 Android12] 添加自定义启动脚本

1:定义添加的脚本 2:rk3568_s.mk 中定义打包 3:在启动脚本中init.rk356x.rc添加权限及何时启动 4:添加权限文件file_contexts 5:系统确认是否运行

OpenWrt/WLAN/驱动/Android/嵌入式开发总结 2219

GEO的工作原理,以及GEO会催生出更多的爬虫岗位吗?

摘要: GEO(生成式引擎优化)是提升内容在AI搜索(如ChatGPT、Perplexity等)中引用率的新策略,核心在于优化内容的可抓取性、语义清晰度、权威性。与传统SEO不同,GEO聚焦AI的引用逻辑,需通过爬虫监控AI回答、逆向分析引用源特征(如结构化数据、权威背书),并构建自动化工具优化内容。爬虫工程师需转型为“AI可见性基础设施构建者”,重点关注高权威站点、知识库及官方信息源,同时确保技术可抓取性(如放行AI爬虫UA)。GEO的核心是从“排名”转向“被AI引用”,强调实体识别与动态对话适配。

数据知道的博客 4640

【leetcode每日刷题】【并查集】547. Friend Circles

There areNstudents in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is adirectfriend of B, and B is adirectfriend of C, then ...

菜菜鸟的博客 231

unity从3D升级到urp管线,打包ab包后,材质全部变紫色

确保材质中的被转换为 URP 兼容的着色器。在打包 AssetBundle 时,确保所需的着色器被正确打包。确保运行 AB 包的目标项目中正确配置了 URP 渲染管线。如果加载后材质丢失,检查 AB 包的加载逻辑,确保材质正确应用了着色器。通过这些步骤,你应该能够解决从标准渲染管线切换到 URP 渲染管线后,材质在 AB 包中变紫色的问题。如果问题仍然存在,请根据具体错误日志进一步排查。希望如上措施及解决方案能够帮到有需要的你。

**My Coding Family** 1962

LeetCode 547 Friend Circles(并查集)

There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, t

nudt_oys的博客 4314

深度学习工具包 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")

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

【小白爬Leetcode547】朋友圈 Friend Circles

【小白爬Leetcode547】朋友圈 Friend Circles 题目Discription思路一 DFS一个错误的想法小聪明,将空间复杂度降为O(1)思路二 BFS思路三 并查集 Leetcode547 medium\color{#FF4500}{medium}medium 点击进入原题链接:单词搜索II Word SearchII 题目 Discription There are N students in a class. Some of them are friends, while som

weixin_41604040的博客 463

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

LeetCode刷题:547. Friend Circles

LeetCode刷题:547. Friend Circles 原题链接:https://leetcode.com/problems/friend-circles/ There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nat...

梅森上校的博客 业精于勤荒于嬉,形成于思毁于随。 352

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

LeetCode Algorithm【547 】Friend Circles

LeetCode

mattmu的博客 545

LeetCode 547 Friend Circles (并查集)

There areNstudents in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is adirectfriend of B, and B is adirectfriend of C, then ...

Tc的专栏 379

Leetcode 547. Friend Circles(python+cpp)

Leetcode 547. Friend Circles题目解析DFS解法BFS解法C++版本DFS 题目 解析 这道题目给的是一个邻接矩阵。乍一看会觉得跟695 max area of islands是一模一样的,其实不然。695的矩阵展示的是每个1和0的实际位置,而这题则不是。应该说695的矩阵表示某种意义上说已经是无向图的一种表示了,但是这道题目不是。 具体的区别是这样的,这题的核心目标是...

qq_37821701的博客 522

leetcode 547. Friend Circles

There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, the

淡然坊 703

LeetCode | 547. Friend Circles 并查集

There are N studentsin a class. Some of them are friends, while some are not. Their friendship istransitive in nature. For example, if A is a direct friendof B, and B is a direct friendof C, then A is...

u012737193的博客 415

547. Friend Circles

305. Number of Islands II方法1: Union find易错点Complexity方法2: dfsComplexity There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For exa...

wilzxu的博客 165

leetcode 547. Friend Circles 并查集

https://leetcode.com/problems/friend-circles/ 朋友关系是双向的,因此矩阵M是关于对角线对称的,只需要处理对角线以上的半边即可。 用一维数组 f [] 记录每个节点真实的根,使用并查集的方式,求出朋友圈的个数。 class Solution { public: int findCircleNum(vector<ve...

rock4you 241

leetcode547: Friend Circles

题目描述: 参考地址: https://www.cnblogs.com/grandyang/p/6686983.html https://blog.youkuaiyun.com/niushuai666/article/details/6662911 有个班级,里面有N个学生,他们之中有些是朋友有些不是,比如如果A是B的朋友,B是C的朋友,那么A就是C的间接朋友,我们定义所谓的朋友圈就是由直系和间接朋友...

wwwsctvcom的博客 392

[LeetCode]547. Friend Circles

[LeetCode]547. Friend Circles题目描述思路dfs 对每个人未访问过的人,确定他最大的朋友圈范围,同时标记已经访问过的人,最后把所有的朋友圈结果加和即为结果代码#include <iostream> #include <vector> #include <algorithm>using namespace std;class Solution { public:

Lcharon的博客 538
上一篇: LeetCode 128: Longest Consecutive Sequence
下一篇: Top K 题目小结
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值