<commit_before>package leetcode;

/**
 * https://leetcode.com/problems/friend-circles/
 */
public class Problem547 {
    public int findCircleNum(int[][] M) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem547 prob = new Problem547();

        System.out.println(prob.findCircleNum(new int[][]{
            {1, 1, 0},
            {1, 1, 0},
            {0, 0, 1}
        })); // 2

        System.out.println(prob.findCircleNum(new int[][]{
            {1, 1, 0},
            {1, 1, 1},
            {0, 1, 1}
        })); // 1
    }
}<commit_msg>Solve problem 547<commit_after>package leetcode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * https://leetcode.com/problems/friend-circles/
 */
public class Problem547 {
    public int findCircleNum(int[][] M) {
        UnionFind uf = new UnionFind();
        for (int i = 0; i < M.length; i++) {
            for (int j = 0; j < M[i].length; j++) {
                if (M[i][j] == 1) {
                    uf.union(i, j);
                }
            }
        }
        return new HashSet<>(uf.map.values()).size();
    }

    private static class UnionFind {
        private final Map<Integer, Integer> map = new HashMap<>();

        public void union(int a, int b) {
            if (!map.containsKey(a)) {
                map.put(a, a);
            }
            if (!map.containsKey(b)) {
                map.put(b, b);
            }
            if (map.get(a) == map.get(b)) {
                return; // already connected
            }
            for (Map.Entry<Integer, Integer> e : map.entrySet()) {
                if (e.getValue().equals(map.get(a))) {
                    map.put(e.getKey(), map.get(b));
                }
            }
        }
    }
}
{'fraction_non_alphanumeric': 0.15853658536585366, 'fraction_numerical': 0.021618625277161862, 'mean_word_length': 1.442489851150203, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 7, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3297681', 'n_tokens_mistral': 612, 'n_tokens_neox': 568, 'n_words': 130}