C++ Easy to Understand DFS Approach


  • 0
    U
    class Solution {
    public:
        vector<int> g[1000];
        int mark[1000]={0};
        int findCircleNum(vector<vector<int>>& M) {
            for(int i=0;i<M.size();i++){
                for(int j=0;j<M[i].size();j++){
                    if(M[i][j]==1 && i!=j){
                        g[i].push_back(j);
                    }
                }
            }
            int ans=0;
            for(int i=0;i<M.size();i++){
                if(!mark[i]){
                    dfs(i);
                    ans++;
                }
            }
            return ans;
        }
        void dfs(int x){
            mark[x]=1;
            for(int i=0;i<g[x].size();i++){
                if(!mark[g[x][i]]){
                    dfs(g[x][i]);
                }
            }
        }
    };
    

Log in to reply
 

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