1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: int findCircleNum(vector<vector<int>>& M) { const int N = M.size(); vector<bool> visited(N, false); int cnt = 0; for (int i = 0; i < N; ++i) if (!visited[i]) { ++cnt; dfs(M, i, visited); } return cnt; } private: void dfs(vector<vector<int>>& M, int i, vector<bool>& visited) { visited[i] = true; for (int j = 0; j < M.size(); ++j) if (M[i][j] && !visited[j]) dfs(M, j, visited); } };
|