LeetCode547 circle of friends

Subject description:

There are students in the class N. Some of them are friends, some are not. Their friendship has is transitive. If you know a friend B of A, B C is a friend, so we can assume that A is C friend. The so-called circle of friends, is the set of all your friends.

Given an N * N matrix M, represents the friendship between classes high school students. If M [i] [j] = 1, represents a known i-th and j-th student mutual friendship, otherwise I do not know. You must be exported to all students in the total number of known circle of friends.

Example 1:

Input:
[[1,1,0],
[1,1,0],

[0,0,1]]
Output: 2
Description: Known students and students 0 1 mutual friends, they are in a circle of friends.
The first two students themselves in a circle of friends. 2 is returned.
Example 2:

Input:
[[1,1,0],
[1,1,1],
[0,1,1]]
Output: 1
Description: known Student Student 0 and 1 mutual friend, a student and the student 2 mutually friends, so students and students 0 2 is also a friend, so three of them in a circle of friends, returns 1.
note:

N within the [1,200] range.
For all students, M [i] [i] = 1.
If M [i] [j] = 1, then there are M [j] [i] = 1.

 

answer:

A typical set of topics and search, of course, DFS can do.

 1 class Solution {
 2     int[] id;
 3     int[] size;
 4     int count=0;
 5     public int findCircleNum(int[][] M) {
 6         if (M==null||M.length==0) {
 7             return 0;
 8         }
 9         DisJointSet(M.length);
10         for (int i=0; i<M.length; i++) {
11             for (int j=i+1; j<M.length; j++) {
12                 if (M[i][j]!=0) {
13                     union(i,j);
14                 }
15             }
16         }
17         return count;
18     }
19     public void DisJointSet(int n) {
20         id=new int[n];
21         size=new int[n];
22         for (int i=0; i<n; i++) {
23             id[i]=i;
24             size[i]=1;
25         }
26         count=n;
27 
28     }
29     public int find(int p) {
30         while (p!=id[p]) {
31             id[p]=id[id[p]];
32             p=id[p];
33         }
34         return p;
35     }
36     public void union(int p,int q) {
37         int i=find(p);
38         int j=find(q);
39         if (i==j) {
40             return;
41         }
42         if (size[i]<size[j]) {
43             id[i]=j;
44             size[j]+=size[i];
45         }else {
46             id[j]=i;
47             size[i]+=size[j];
48         }
49         count--;
50     }
51 }

Comments are welcome, and common progress! !

Guess you like

Origin www.cnblogs.com/hengzhezou/p/11070345.html