C++ DFS


  • 0
    B
    class Solution {
    public:
        int cnt = 0;
        int findCircleNum(vector<vector<int>>& M) {
            vector<int> visited(M.size(),0);
            for (int i = 0; i < visited.size(); i++) { 
                if (visited[i] == 1) continue;
                cnt++;
                dfs(M, visited, i);
            }
            return cnt;
        }
        void dfs(vector<vector<int>>& M, vector<int> &visited, int node) {
            if (visited[node] == 1) return;
            visited[node] = 1;
            for (int i = 0; i < M.size(); i++) {
                if (M[node][i] == 1) {
                    dfs(M, visited, i);
                }
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.