Concise Java solution, DFS


  • 0
    Y
        public int findCircleNum(int[][] M) {
        	int num = 0;
            for (int i = 0; i < M.length; i++) 
            	if (M[i][i] < 2) findFriend(M, num++, i);
        	return num;
        }
        private void findFriend(int[][] M, int num, int row) {
        	M[row][row] = 2;
        	for (int i = 0; i < M.length; i++) 
        		if (M[row][i] != 0 && M[i][i] < 2) findFriend(M, num, i);
        }
    

Log in to reply
 

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