547. Friend Circles(朋友圈)

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

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);
            }
        }
        
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝羽飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值