LeetCode No.6 朋友圈

1. LeetCode547题目链接链接

https://leetcode-cn.com/problems/friend-circles/

2.题目解析

循环遍历每个节点,如果这个节点未访问过,朋友圈数量+1,然后在找这个节点能够访问的所有的点,修改数组中标志。

public int findCircleNum(int[][] M) {
        /**
         使用一个visited数组, 依次判断每个节点, 如果其未访问, 朋友圈数加1并对该节点进行搜索标记所有访问到的节点
         **/
        boolean[] data = new boolean[M.length];
        int count = 0;
        for(int i = 0; i < M.length; ++i) {
            if(!data[i]) {
                search(M, data, i);
                count++;
            }
        }
        return count;
    }

    private void search(int[][] m, boolean[] data, int i) {
        for(int j = 0; j < m.length; ++j) {
            if(m[i][j] == 1 && !data[j]) {
                data[j] = true;
                search(m, data, j);
            }
        }
    }

3.提交结果

提交结果
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容