1. LeetCode547题目链接链接
https://leetcode-cn.com/problems/friend-circles/
2.题目解析
循环遍历每个节点,如果这个节点未访问过,朋友圈数量+1,然后在找这个节点能够访问的所有的点,修改数组中标志。
public int findCircleNum(int[][] M) {
/**
使用一个visited数组, 依次判断每个节点, 如果其未访问, 朋友圈数加1并对该节点进行搜索标记所有访问到的节点
**/
boolean[] data = new boolean[M.length];
int count = 0;
for(int i = 0; i < M.length; ++i) {
if(!data[i]) {
search(M, data, i);
count++;
}
}
return count;
}
private void search(int[][] m, boolean[] data, int i) {
for(int j = 0; j < m.length; ++j) {
if(m[i][j] == 1 && !data[j]) {
data[j] = true;
search(m, data, j);
}
}
}
3.提交结果
提交结果