You can try to set j in dfs to a special start in order to decrease the number of loops

public int findCircleNum(int[][] M) { int len = M.length; boolean[] set = new boolean[len]; int count = 0; for(int i=0;i<len;i++){ if(!set[i]){ count++; dp(M,i,i,set); } } return count; } public void dp(int[][] M,int loopstart,int start,boolean[] set){ for(int j=loopstart;j<M.length;j++){ if(M[start][j]==1&&!set[j]){ set[j] = true; dp(M,loopstart,j,set); } } }And this code is faster than 99% Java solution :P