(这道题还可用BFS做。做法看BFS的例题整理)
class Solution {
public:
void dfs(vector<vector<int>>& isConnected, int index, int size, vector<int>& visit) {
for (int i = 0; i < size; ++i) {
if (isConnected[index][i] == 1 && visit[i] == 0 ) {
visit[i] = 1;
dfs(isConnected, i, size, visit);
}
}
}
int findCircleNum(vector<vector<int>>& isConnected) {
int size = isConnected.size();
vector<int> visit(size, 0);
int res = 0;
for (int i = 0; i < size; ++i) {
if (visit[i] == 0) {
res++;
dfs(isConnected, i, size, visit);
}
}
return res;
}
};