Java 12ms solution with short explaination.


  • 1

    Java 12ms solution with short explaination.

       Iterate the student list and update the visited[] continuesly 
       by searching the M[][] and update the circle.
    */
    
    public class Solution {
        private boolean[] visited;
        public int findCircleNum(int[][] M) {
        	
        	if(M.length<=1) return M.length;
        	
            int circle = 0;
            visited = new boolean[M.length];
            
            for(int i=0;i<visited.length;i++){
            	if(!visited[i]){
            		circle++;
            		visitCircle(M, i);
            	}
            }
            return circle;
            
        }
    
        private void visitCircle(int[][] M, int i){
        	if(visited[i]) return;
        	visited[i] = true;
        	
        	for(int j=0;j<M[i].length;j++){
        		if(M[i][j]==1 && j!=i){
        			visitCircle(M,j);
        		}
        	}
        }
        
    }

Log in to reply
 

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