FindUnion short Java clean code


  • 0

    Find Union.

    public class Solution {
        int[] flag;
        public int findflag(int i ){
            if(flag[i] == i)
            return i;
            return findflag(flag[i]);
        }
        public int findCircleNum(int[][] M) {
            int N = M.length;
            flag = new int[N];
            Set<Integer> set = new HashSet<>();
            for(int i = 0 ; i < N ; i++){
                flag[i] = i;
            }
            for(int i = 0 ; i < N ; i++){
                for(int j = 0; j < i; j ++){
                    if(M[i][j] == 1){
                        int parenti = findflag(i);
                        int parentj = findflag(j);
                        flag[parentj] = parenti;
                    }
                }
            }
            for(int i = 0; i < N ; i++){
                set.add(findflag(i));
            }
            return set.size();
        }
    }

Log in to reply
 

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