题目:
分析:根据题目很容易想到无向图的深度优先搜索,其实这个朋友圈的也就是深度优先搜索问题因为条件说了朋友具有传递性
代码:
class Solution {
public int findCircleNum(int[][] M) {
boolean[] marked = new boolean[M.length];
int circle = 0;
for(int i = 0; i < M.length; i++){
if(!marked[i]){
dfs(M, i, marked);
circle++;
}
}
return circle;
}
static void dfs(int[][] M, int i, boolean[] marked){
marked[i] = true;
for(int j = 0; j < M[0].length; j++){
if(M[i][j] == 1 && marked[j] == false){
dfs(M, j, marked);
}
}
}
}