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);
}
}
}