算法训练:Friend Circles

来源:互联网 发布:淘宝怎么用银行卡分期 编辑:程序博客网 时间:2024/05/15 23:44

题目链接:https://leetcode.com/problems/friend-circles/#/description


题目描述:

      朋友圈: 如果A和B是好朋友,B和C是好朋友,则A、B、C属于一个朋友圈。

      现用一个二维矩阵M来记录N个人的关系,M[i][i]=1,如果 i 和 j 是好友,M[i][j]=1,否则等于0。

      题目要求求N个人组成的朋友圈的数目。

   Example 1:

Input: [[1,1,0], [1,1,1], [0,1,1]]Output: 1Explanation: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.
  Example 2:
Input: [[1,1,0], [1,1,0], [0,0,1]]Output: 2Explanation: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.

解题思路:

   DFS:对一个人i,遍历其好友,然后在遍历其好友的好友,这样可以遍历出一条朋友圈,朋友圈数加1。在遍历的时候用一个数

               组标记已访问过的人,在一条朋友圈访问结束后,再对未访问过的人进行同样的操作,直到所有的人已经访问结束。

    BFS:对一个人i,遍历所有其未被访问过的好友,用一个队列来记录下这些好友,当i的所有的好友访问结束后,我们再从队列中

              取出一个好友,进行同样的操作,当队列为空的时候,朋友圈数加1。再对未访问过的人进行同样的操作,直到所有的人

              已经访问结束。

     //DFS    void visitNext(vector<vector<int>>& M, int curPoint, vector<int>& visited) {        visited[curPoint] = true;        for (int j = 0; j < M.size();j++) {            if (M[curPoint][j] && visited[j]==0) visitNext(M, j, visited);        }    }    int findCircleNum(vector<vector<int>>& M) {        int row=M.size();        int col=M[0].size();        if(row==0) return 0;        int circleNum=0;        vector<int> visited(row,0);        for(int i=0;i<row;i++){            if(visited[i]==0){//未被访问过                visitNext(M,i,visited);                circleNum++;            }        }        return circleNum;    }

运行结果:

Your Input
[[1,1,0,0],[1,1,0,1],[1,0,1,1],[0,1,1,1]]
Your answer
1
Expected answer
1










原创粉丝点击