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 indirectfriend 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.
Note:
- N is in range [1,200].
- M[i][i] = 1 for all students.
- If M[i][j] = 1, then M[j][i] = 1.
使用DFS,类似于连通图
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 class Solution {//DFS mytip 2 public int findCircleNum(int[][] M) { 3 if(null==M||0==M.length){ 4 return 0; 5 } 6 int row =M.length; 7 int re = 0; 8 boolean[] visited=new boolean[row]; 9 for(int i=0;i<row;i++){ 10 if(!visited[i]){ 11 dfs(M,visited,i); 12 re++; 13 } 14 } 15 return re; 16 } 17 private void dfs(int[][] M,boolean[] visited,int i){ 18 if(i<0||i>=M.length){ 19 return; 20 } 21 visited[i]=true; 22 for(int j=0;j<M.length;j++){ 23 if(!visited[j]&&1==M[i][j]){ 24 dfs(M,visited,j); 25 } 26 } 27 } 28 }
使用并查集
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 class Solution {//并查集 my 2 public int findCircleNum(int[][] M) { 3 if(null==M||0==M.length){ 4 return 0; 5 } 6 int row =M.length; 7 UnionFind uf = new UnionFind(row); 8 for(int i=0;i<row;i++){ 9 for(int j=i+1;j<row;j++){ 10 if(1==M[i][j]){ 11 uf.union(i,j); 12 } 13 } 14 } 15 return uf.getCount(); 16 } 17 } 18 19 class UnionFind{ 20 private int[] parents;//根节点 21 private int count; 22 public UnionFind(int n){ 23 parents= new int[n]; 24 for(int i=0;i<n;i++){ 25 parents[i]=i; 26 } 27 count = n; 28 } 29 30 public int getCount(){ 31 return this.count; 32 } 33 public int find(int x){ 34 int root = x; 35 while(root!=parents[root]){ 36 root= parents[root]; 37 } 38 while(parents[x]!=root){ 39 int tmp = parents[x]; 40 parents[x] =root; 41 x = tmp; 42 } 43 return root; 44 } 45 public void union(int x,int y){ 46 int rootx = find(x); 47 int rooty = find(y); 48 if(rootx!=rooty){ 49 parents[rooty] = rootx; 50 count--; 51 } 52 53 } 54 }