547. Friend Circles

Problem:
There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.
Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.
Example 1:
Input: 
[[1,1,0],
 [1,1,0],
 [0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. 
The 2nd student himself is in a friend circle. So return 2.
Example 2:
Input: 
[[1,1,0],
 [1,1,1],
 [0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, 
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
Note:
  1. N is in range [1,200].
  2. M[i][i] = 1 for all students.

Analysis:
Light version of number of islands. Item in union find reduces from 2d to 1d. 

Solution:

class Solution {
    class Union_Find {
        private int[] father;
        public int count = 0;
        public Union_Find(int[][] grid, int m) {
            father = new int[m];
            count = m;
            for (int i = 0; i < m; i++) {
                father[i] = i;
            }
                
        }

        public void connect(int a, int b) {
            int root_a = find(a);
            int root_b = find(b);
            if (root_a != root_b) {
                father[root_a] = root_b;
                count--;
            }
        }

        public int find(int n) {
            if (father[n] == n) 
                return n;
            return father[n] = find(father[n]);
        } 

        public boolean query(int a, int b) {
            int root_a =  find(a);
            int root_b = find(b);
            return root_a == root_b;
        }
    } 

    public int findCircleNum(int[][] M) {
        if (M == null || M.length == 0 || M[0].length == 0)
            return 0;
        int[][] dirs = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        int m = M.length;
        int n = M[0].length;
        Union_Find uf = new Union_Find(M, m);
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) { 
                if (M[i][j] == 1) {
                    uf.connect(i, j);
                }
            }

        return uf.count;
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List