547. Friend Circles(朋友圈)

本文介绍了一种基于矩阵的算法,用于计算一个班级中学生形成的朋友圈总数。通过深度优先搜索(DFS)遍历N*N的矩阵,算法能够识别出直接和间接的朋友关系,并将他们归入同一朋友圈。具体实现中,利用一维数组visited标记已访问过的朋友,避免重复计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

给出一个N*N矩阵M,M(i,j) = 1表示 i 和 j 是朋友,而且朋友有传递性,A和B是朋友,B和C是朋友,那么A和C也是间接的朋友,让找出有几个朋友圈,其中一个人可以是他自己的朋友。

思路:
矩阵M是N*N的,而且M(i,j) = M(j, i), 一共N个人,那么可以取一维数组visited判断第i个人的朋友是否已经找过。
即找无向图的强连通区域,如果现在在看第i个人,那么取第i行,再遍历这行的所有列,看谁是i的朋友,如果M(i,j) == 1, 说明 j 是 i 的朋友,那么再去找 j 的朋友(访问第 j 行,以此类推,DFS),直到找到 i 所有直接和间接的朋友,访问过的在visited里标为true

    public int findCircleNum(int[][] M) {
        if(M == null || M.length == 0) {
            return 0;
        }
        
        int res = 0;
        int n = M.length;
        boolean[] visited = new boolean[n];
        for(int r = 0; r < n; r++) {
            if(visited[r]) {
                continue;
            }
            
            dfs(M, visited, n, r);
            res ++;
        }
        
        return res;
    }
    
    public void dfs(int[][] M, boolean[] visited, int n, int r) {
        if(visited[r]) {
            return;
        }
        visited[r] = true;
        
        for(int c = 0; c < n; c++) {
            if(M[r][c] == 1 && !visited[c]) {
                dfs(M, visited, n, c);
            }
        }
        
    }
### 力扣上的并查集示例题目 #### 题目概述 在 LeetCode 上,并查集是一种非常常见的算法设计模式,用于解决涉及连通性和分组的问题。以下是几个经典的并查集相关题目及其描述。 --- #### 经典题目解析 1. **岛屿数量 (Number of Islands)** 这是一个经典问题,目标是在二维网格中计算由 '1' 表示的陆地组成的岛屿的数量[^2]。可以使用 DFS、BFS 或者并查集来实现。如果选择并查集方法,则可以通过 `union` 操作将相邻的陆地标记为同一集合,最终统计独立集合的数量得到答案。 2. **最长连续序列 (Longest Consecutive Sequence)** 输入一个未排序的整数数组,找到其中最长的连续子序列长度[^3]。此问题可以用哈希表或者并查集求解。通过构建节点之间的连接关系,利用并查集中的 `find` 和 `union` 方法动态维护最大连通区域大小。 3. **朋友圈 (Friend Circles)** 描述了一群学生之间是否存在友谊关系的情况,判断总共有多少个互不相交的朋友圈[^1]。这道题可以直接映射到标准的并查集模型上——每一对朋友视为一条边,执行相应的合并操作后查询总的连通分支数目即可得出结果。 4. **账户合并 (Accounts Merge)** 提供多个电子邮件地址列表以及它们所属用户的姓名信息,要求按照实际拥有这些邮箱的人重新整理输出形式[^4]。这里同样适用基于字符串键值建立图结构再借助并查集完成归类处理逻辑。 5. **冗余连接 II (Redundant Connection II)** 假设树形拓扑被破坏成含有环路的状态,请找出造成这种情况的一条多余边并移除恢复原状。运用带权版并查集技巧检测何时形成闭环从而定位错误链接位置。 --- ```python class UnionFind: def __init__(self, n): self.parent = list(range(n)) def find(self, p): while p != self.parent[p]: self.parent[p] = self.parent[self.parent[p]] # 路径压缩 p = self.parent[p] return p def union(self, p, q): rootP = self.find(p) rootQ = self.find(q) if rootP == rootQ: return False self.parent[rootP] = rootQ return True ``` 上述代码片段展示了如何定义一个基础版本的支持按秩合并与路径压缩优化后的并查集数据结构实例化过程。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值