Share my java dfs solution


  • 0
    A

    Share my java dfs solution:

    public int findCircleNum(int[][] M) {
        if(M == null) return 0;
        int count = 0;
        for (int i=0; i<M.length; i++){
            if(M[i][i] == 1){
                count ++;
                dfs(M, i);
            }
        }
        
        //set the diagonal back
        for(int i=0; i<M.length; i++){
            if(M[i][i] == 2) M[i][i] = 1;
        }
        
        return count;
    }
    
    private void dfs(int[][] M, int student){
        M[student][student] = 2;
        for(int i=0; i<M[student].length; i++){
            if(M[student][i]==1 && M[i][i] == 1){
                dfs(M, i);
            }
        }
    }

Log in to reply
 

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