topic
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:
Enter:
[[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.
Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/friend-circles
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
answer
Undirected graph given matrix adjacent to , the number of branches communicating undirected graph requirements.
Here the use of DFS, in particular, the use of a one-dimensional matrix represents the access point or not .
Code
class Solution {
public int findCircleNum(int[][] M) {
boolean[] visited=new boolean[M.length];
int cnt=0;
for(int i=0;i<visited.length;++i){
if(!visited[i]){
dfs(M,visited,i);
cnt++;
}
}
return cnt;
}
private void dfs(int[][] M,boolean[] visited,int i){
visited[i]=true;
for(int j=0;j<M.length;++j){
if(!visited[j]&&M[i][j]==1){
dfs(M,visited,j);
}
}
}
}