Java-DFS Solution, quite easy for understanding


  • 0
    F
        
        int[] mark;
        
        public int findCircleNum(int[][] M) {
            int count=0;
            mark=new int[M.length];
            for(int i=0;i<M.length;i++){
                if(mark[i]==0){
                    dfs(M,i);
                    count++;
                }
            }
            return count;
        }
        
        private void dfs(int[][] M,int i){
            if(mark[i]==1)return;
            mark[i]=1;
            for(int j=0;j<M.length;j++){
                if(M[i][j]==1&&i!=j){
                    dfs(M,j);
                }
            }
        }
    }
    

Log in to reply
 

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